设备进入待机状态后,如果我呼叫getSupportFragmentManager(),则会得到一个FragmentManager,其中包含未初始化且其所有变量都设置为null的片段。

这里有一些代码:

this.mAdapter = new MyAdapter(getSupportFragmentManager());

this.mPager = (ViewPager) findViewById(R.id.pager);
this.mPager.setAdapter(mAdapter);

TabPageIndicator titleIndicator = (TabPageIndicator) findViewById(R.id.titles);
titleIndicator.setViewPager(mPager);
titleIndicator.setOnPageChangeListener(new OnPageChangeListener()
{
    @Override
    public void onPageSelected(int position)
    {
        mAdapter.getItem(position).onFocus();
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2)
    {
    }

    @Override
    public void onPageScrollStateChanged(int arg0)
    {
    }
});


这是MyAdapter类:

public static class MyAdapter extends FragmentStatePagerAdapter
{
    ArrayList<ExtendedFragment> tabs = new ArrayList<ExtendedFragment>();
    String[] titles = new String[] { "FRAG1", "FRAG2", "FRAG3", "FRAG4", "FRAG5", "FRAG6"};

    public MyAdapter(FragmentManager fm)
    {
        super(fm);

        tabs.add(new frag1());
        tabs.add(new frag2());
        tabs.add(new frag3());
        tabs.add(new frag4());
        tabs.add(new frag5());
        tabs.add(new frag6());
    }

    @Override
    public int getCount()
    {
        return tabs.size();
    }

    @Override
    public ExtendedFragment getItem(int position)
    {
        return tabs.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position)
    {
        return titles[position];
    }
}


ExtendedFragment实现方法onFocus(),每个片段都覆盖该方法,因为当选项卡获得焦点时,我需要执行一些操作。当我从待机状态恢复设备并触发onFocus()时,如果尝试使用View获取getView(),则会得到null

为什么我的视图为空?

最佳答案

您可以尝试覆盖onSaveInstanceState方法。

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState != null) {
                mContentFragment = getSupportFragmentManager().getFragment(
                        savedInstanceState, "mContent");
            }
            if (mContentFragment == null) {
                mContentFragment = new YourFragment();
            }
    }

    public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            getSupportFragmentManager().putFragment(outState, "mContent",
            mContentFragment);
    }

10-06 03:25