Thijs93H
Thijs93H

Reputation: 184

Change fragment layout dynamically instead of replacing fragments Android SDK

I'm trying make an app that displays a big amount of text and images in a specific layout when the user clicks on a corresponding listview item. Since I want specific .xml layouts for separate 'chapters', I want only the layout of a fragment to change to the corresponding chapter.

Googling tells me I can do this with fragments, but as far as I understand, I need separate fragment classes and .xml layouts for every chapter I want to implement. With 2 or 3 chapters, that can be done, but with more chapters that will become I thought, isn't it simpler to just keep two fragments (one with a listview and one with the chapter text), but dynamically change the layout of the second fragment if the user clicks on an item in the listview.

Can this be done with some code like this (just thinking out loud)?

Int[] layouts = {
        {R.layout.chapter1, R.layout.chapter2, R.layout.chapter3}
    };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    index = intent.getIntent("index", 0);
    return inflater.inflate(layouts[index], container, false);
}

Or is there another way to achieve this?

Upvotes: 4

Views: 5485

Answers (1)

DeeV
DeeV

Reputation: 36035

Fragments at their core are View wrappers that contains states of Views. You can use them for other purposes like resource handling, but mostly they're just segments of an Activity state. It most likely would not be a good idea to have a Fragment for every single chapter unless each chapter has their own unique state that needs to be kept. However, if the Views are static, then a single Fragment is all you really need.

In this case, you simply have to have a method like this:

public void setChapter(int chapter)
{
   Context ctx = getActivity();
   if(ctx == null) {
      // detached from Activity, so bail.
      return;
   }

   if(chapter > layouts.length) {
     return;
   }

   ViewGroup container = (ViewGroup) getView().findViewById(R.id.chapter_container);
   container.removeAllViews();
   View chapterInflater = LayoutInflater.from(ctx).inflate(layouts[chapter], container);
}

So this will wipe out all views currently in your container, inflate a new one, and put it in the container (most likely a simple FrameLayout).

The code in the original question can be used to initialize a Fragment if you want to open it at a certain point. onCreate_() methods are called only when the items is being "built" or "created". onCreateView() won't be called again though, so you need a method to change the layout once it's set.

Upvotes: 5

Related Questions