1

I got 3 tabs however I got one fragment. Is it possible to use one fragment for the 3 tabs ?

Currently I have this in my FragmentPagerAdapter:

@Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return new FragmentTwo(region,"1");
            } else if(position == 1){
                return new FragmentTwo(region,"2");
            }
            return new FragmentTwo(region,"3");
        }

But only showing all data in one tab..

I've edited my code but still getting all data in one tab. Currently :

@Override
        public Fragment getItem(int position) {
            return FragmentTwo.newInstance(region, position);
        }

&&

static FragmentTwo newInstance(String region,int position) {
        FragmentTwo frag=new FragmentTwo();
        Bundle args=new Bundle();
        args.putInt("KEY_POSITION", position);
        args.putString("REGION", region);
        if(position == 0){
            args.putString("TYPE","A");
        }
        else if(position == 0){
            args.putString("TYPE","B");
        }
        else{
            args.putString("TYPE","C");
        }
        frag.setArguments(args);

        return(frag);
    }

For creating my FragmentPagerAdapter I am calling getSupportFragmentManager();

David
  • 840
  • 6
  • 17
  • 37
  • 1
    You are welcome to use the same fragment class for all tabs. Here is one of my samples that does so: https://github.com/commonsguy/cw-omnibus/tree/master/ViewPager/Fragments – CommonsWare Jan 20 '15 at 21:49
  • I think the question is how to use the same Fragment class instance, and not the Fragment class. – teamnorge Jul 25 '15 at 12:06

1 Answers1

1

Yes you can create an instance of your FragmentTwo, save it in a field/variable, and use it as return data in your function.

One thing to note is that you shouldn't be using constructors with parameters for Fragments. Use Bundle with arguments. Constructors with parameters will potentially cause problems with Fragments.

Take a look at this post regarding that: Best practice for instantiating a new Android Fragment

Community
  • 1
  • 1
JanBo
  • 2,925
  • 3
  • 23
  • 32
  • I implemented it but still getting all data in one tab. Check edit . Thanks :) – David Jan 20 '15 at 22:28
  • 1
    You are still creating a new instance of your fragments... you are still calling FragmentTwo frag=new FragmentTwo(); which creates a new fragment. You need to create your fragment ONLY ONCE and save the instace to a variable for example private FragmentTwo mFragment; and then return this instance. And create a public method which resets your data in you fragment. – JanBo Jan 20 '15 at 22:37