应用程序未使用时未附加的碎片

时间:2017-11-22 12:00:02

标签: android android-fragments

有时getActivity()会返回null,而不应该返回null。 我认为应用程序没有被使用一段时间后,活动可能会被杀死。添加片段我错了吗?

同样有趣的事情:

fragmentWatchList = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 0);

这段代码永远找不到片段。有人知道为什么吗? (R.id.viewpager是正确的,也尝试使用viewPager.getId())

我用这种方式添加片段:

protected void setupViewPager(ViewPager viewPager) {
    List<Fragment> fragments = getSupportFragmentManager().getFragments();
    if (fragments != null && fragments.size() == 3) {
        fragmentWatchList = fragments.get(0);
        fragmentSignalsList = fragments.get(1);
        fragmentCoinList = fragments.get(2);
    }

   // fragmentWatchList = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 0);
    if (fragmentWatchList == null)
        fragmentWatchList = new WatchListTabFragment();

    //fragmentSignalsList = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 1);
    if (fragmentSignalsList == null)
        fragmentSignalsList = new SignalsTabFragment();

   // fragmentCoinList = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 2);
    if (fragmentCoinList == null)
        fragmentCoinList = new CoinsTabFragment();

    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    viewPagerAdapter.addFragment(fragmentWatchList);
    viewPagerAdapter.addFragment(fragmentSignalsList);
    viewPagerAdapter.addFragment(fragmentCoinList);

    viewPager.setAdapter(viewPagerAdapter);
}

2 个答案:

答案 0 :(得分:0)

当您通过findFragmentByTag将标签设置为您的呼叫片段时,FragmentManager有效。像这样:

Fragment f = new Fragment();

getSupportFragmentManager().beginTransaction().replace(id,f, "tag_comes_here").commit();

此外,getActivity()返回null主要是因为片段已从保留活动中删除。因此,对片段内的异步调用进行isAdded()检查是有好处的。

查看此帖子here,其中简要介绍了isAdded()的用法以及为什么需要

快乐编码〜

答案 1 :(得分:0)

实现常规 FragmentPagerAdapter 的正确方法是:

public class ViewPagerAdapter extends FragmentPagerAdapter {
    public ViewPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0) return new RulesFragment();
        if(position == 1) return new TreeFragment();
        if(position == 2) return new PredictionFragment();

        throw new IllegalStateException("Unexpected position " + position);
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if(position == 0) return "TREE RULES";
        if(position == 1) return "REGRESSION TREE";
        if(position == 2) return "PREDICTION";
      
        throw new IllegalStateException("Unexpected position " + position);
    }
}

要获取对 ViewPager 创建的 Fragment 的引用,请使用以下 findFragmentByTag 方案:

Fragment fragment = supportFragmentManager.findFragmentByTag("android:switcher:" + viewPager.getId() + ":" + fragmentPosition)