I was wondering if it is possible to run fragment on a variable name instead of hard-coding the name fragments .
Let me post a sample
Here's how you traditionally run a snippet:
FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.your_placehodler, new YourFragment()); ft.commit();
But say that you are trying to run a fragment without knowing its name, or perhaps it is a fragment . Say like listFragment , or Listview , and you use the array names from fragment . Therefore, 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) {
I know this is not true, but I feel that, if possible, I can be there. I searched for a while but found nothing.
So my question is: is this possible? If so, how do I implement this? Thanks!
Edit I tried to understand what I thought could 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'
But if in my code I change the line to say Fragment frags = (Fragment) Class.forName("com.android.example." + "Ovens").newInstance();
Works
The "questions" variable is an exact copy of the class name. I do not understand why this will not work. Nothing happens, nothing prints on logcat
Final editing
Got! I missed the marker. Here is the final working code, thanks for 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) { } } }