I was wondering if it was possible to launch a fragment
by variable
name rather then hard coding the fragments
name.
Allow me to post a sample
This is how you traditionally launch a fragment:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.your_placehodler, new YourFragment());
ft.commit();
But say you are trying to launch the fragment
without knowing the name of it, or possibly which fragment
it is. Say like a listFragment
, or a Listview
and you are running through an array
of Fragment
names. Hence you would do something like this:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
private String[] values = new String[] { "frag1", "frag2", "frag3" };
String someFragment = values[position];
String fragName = (someFragment + ".class");
try {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.your_placehodler, new fragName());
ft.commit();
} catch (Exception e) {
//print message
}
I know this is not correct, but I feel like if it's possible I may be close. I searched for a while but I found nothing.
So my question, Is this possible? If so how would I implement it? Thanks!
Edit I attempted what I thought may work with the Reflections API using this code
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String questions = values[position];
try {
Fragment frags = (Fragment) Class.forName("com.example.android." + questions).newInstance();
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out)
.replace(R.id.header_fragment_container, frags).commit();
}
catch (Exception e) {
}
}
}
I get a message saying
05-08 04:38:14.124: W/dalvikvm(812): dvmFindClassByName rejecting 'com.android.example.Ovens'
Yet if in my code I change the line to say
Fragment frags = (Fragment) Class.forName("com.android.example." + "Ovens").newInstance();
It works
The variable "questions" is an exact copy of the class name. I don't see why it wouldn't work. Nothing happens, nothing prints to the logcat
Final Edit
Got it! I was missing the "" marker. Here is the final working code, thanks for all the help
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String questions = values[position];
try {
Fragment frags = (Fragment) Class.forName("com.android.example." + "" + questions).newInstance();
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out)
.replace(R.id.header_fragment_container, frags).commit();
}
catch (Exception e) {
}
}
}