gpt4 book ai didi

android - getSupportFragmentManager() 在待机后包含空 fragment

转载 作者:行者123 更新时间:2023-11-29 18:05:55 25 4
gpt4 key购买 nike

设备进入待机状态后,如果我调用 getSupportFragmentManager(),我会得到一个 FragmentManager,其中包含未初始化的 fragment ,其所有变量都设置为 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(),每个 fragment 都会覆盖它,因为我需要在选项卡获得焦点时执行一些操作。当我从待机状态恢复设备并且 onFocus() 被触发时,如果我尝试使用 getView() 获取 View 我会得到

为什么我的 View 是空的?

最佳答案

您可以尝试覆盖 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);
}

关于android - getSupportFragmentManager() 在待机后包含空 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13377828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com