ViewPager bug if i turn on the screen again

282 views Asked by At

I have NavigationDrawer, when I select fragment with ViewPager in first time, all work good, but if I select this item the second time or more, I see white screen, because don't call onViewCreated at fragments in ViewPager. How I can fix it?

Set fragment with ViewPager:

getSupportFragmentManager().beginTransaction()
    .replace(R.id.container, fragment)
    .commit();

For ViewPager i used FragmentPagerAdapter:

@Override
    public Fragment getItem(int position) {
        Fragment fragment = null;

        switch (position) {
            case 0:
                fragment = new Fragment1();
                break;
            case 1:
                fragment = new Fragment2();
                break;
            case 2:
                fragment = new Fragment3();
                break;
        }

        return fragment;
    }

Code in Fragment1, Fragment2 and Fragment3:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getData(); // get Data from internet

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        adapter = MyAdapter(getActivity(), R.layout.item_best, objects);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(onRefreshListener);
        if (objects.size() == 0) {
            swipeRefreshLayout.setRefreshing(true);
        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ...
    }
1

There are 1 answers

2
Muthukrishnan Suresh On
View layout =  inflater.inflate(R.layout.your_layout, container, false);

    adapter = MyAdapter(getActivity(), R.layout.item_best, objects);
    listView = (ListView) layout.findViewById(R.id.listView);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(this);
    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
    swipeRefreshLayout.setOnRefreshListener(onRefreshListener);
    if (objects.size() == 0) {
        swipeRefreshLayout.setRefreshing(true);
    } 

getData();

    return layout;

Try similarly in onCreateView