0

I'm working on a simple Android App as a self-learning Project. I've got a lot of it functioning, and I have a main Activity which has a FrameLayout and some RecyclerView and FloatingActionButton stuff going on inside of it.

However, I want to make one of my buttons in my NavigationDrawer open a different view in the FrameLayout using Fragments. Is there a way to do this, sort of making a new Fragment for the RecyclerView and the other stuff and putting the RecyclerView and FloatingActionButton in there?

I tried doing something like this (when the appropriate NavigationDrawer button was clicked):

statsFragment = new StatsFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.rootLayout, statsFragment);
        transaction.addToBackStack(null);
        transaction.commit();

But this caused my app to crash. Any pointers?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
Jake Chase
  • 27
  • 1
  • 5

1 Answers1

0

Is your R.id.rootLayout a Layout or a Fragment component?

If your main Activity has a hard coded Fragment (by hard coded i mean declared in your XML), then no, you can't change a hard-coded fragment content with FragmentTransaction. More information on this question's answer.

Finally, you can't put your components from one Activity inside a new Fragment/Activity since each component belongs to one and only one Context. See, Activity extends Context. When you get a reference to a component declared in your XML by using Activity.findViewById(int), you are actually making a pointer to a determined View from this Activity's layout, defined in your onCreatemethod with setContentView(id). You can't take this pointer and throw it to another Fragment or Activity within your application without expecting any problems. (Well, maybe you can, but it's totally against the best practices of Android Programming).

Community
  • 1
  • 1
VulfCompressor
  • 1,390
  • 1
  • 11
  • 26