1

How to load one tab of viewpager at a time ??

I want develop dynamic Tabs with same kind of Fragments.But the problem is ViewPager loads the 2 tab at time and when i change some data in one fragment it will reflects on every fragments.enter image description here

Patel Jaimin
  • 231
  • 1
  • 11

2 Answers2

0

You can override this method inside of fragment, this will return true if this fragment is in front of screen

 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //You can do inside this method
        }
    }

}

Mohit Suthar
  • 8,725
  • 10
  • 37
  • 67
saurabh dixit
  • 863
  • 6
  • 19
0

you can use yourViewPager.setOffScreenPageLimit(value) method. But minimum value of pre-loaded pages is 1, so at least 1 page always will be cached.

To set correct data to page of viewPager you can do something like this:

public class YourFragment extends Fragment{
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
int pos;

static YourFragment newInstance(int page) {
    YourFragment yourFragment = new YourFragment();
    Bundle arguments = new Bundle();
    arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
    yourFragment.setArguments(arguments);
    //save fragment position
    return yourFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        pos = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
        //now you have position of this fragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View yourView = inflater.inflate(R.layout.your_fragment_layout, container, false);
   //use position of the fragment you received in onCreate to set up your views
    return yourView;
}
Sc222
  • 9
  • 4
  • see this answer, it is impossible to load less than 2 tabs at time https://stackoverflow.com/a/10073916/8472252 – Sc222 Aug 21 '17 at 07:29