Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Instantiate a Fragment multiple times?

I'm creating an app that displays data in a ListView. Data is categorized in let say two types (Popular, Favorites). I have one Activity and two Fragments. The Fragments displays a list of items based on their category. I used a ListView for this. I then have two fragment_layouts which are exactly alike in design but have different view id's ie tvId1, tvId2 for TextViews. The codes in the Fragments only differ in referencing their corresponding layout and views in the layout. I get data from a URL which is in JSON format. But each category has a different set of URL which produces the same structure just different data. I then parse the corresponding URL on each Fragment and populate the ListView accordingly. Everything works so far.

What I want to know, is there a way that I can just use one Fragment and use it two times with different set of data in each? This way I don't have to create another Fragment if a new category comes up.

Appreciate any help.

like image 328
user2469412 Avatar asked Jul 16 '13 12:07

user2469412


1 Answers

Of course you can do. In fact you should do it like this.

When you are creating the Fragment do not use new Fragment(); Create a static newInstance function that take the data as argument.

public static MyFragment newInstance(int type) {
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    args.putInt("type", type);
    fragment.setArguments(args);
    return fragment;
}

And then you can get the type on onCreate() method using below:

getArguments().getInt("type");

And then you get the type, you can call your webservice accordingly, and then you can set the Views accordingly.

like image 114
tasomaniac Avatar answered Nov 07 '22 23:11

tasomaniac