如果我再次打开屏幕,则会出现ViewPager错误

时间:2015-06-08 15:48:27

标签: android android-fragments android-viewpager

我有NavigationDrawer,当我第一次选择带有ViewPager的片段时,一切正常,但如果我第二次选择此项目,我会看到白色屏幕,因为不是&#39 ; t在onViewCreated中的片段中调用ViewPager。我怎么解决它?

使用ViewPager设置片段:

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

对于ViewPager,我使用了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;
    }

Fragment1Fragment2Fragment3中的代码:

@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 个答案:

答案 0 :(得分:0)

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;

在onCreateView中尝试类似