gpt4 book ai didi

android - Fragment 的 GetTag 返回空对象引用

转载 作者:行者123 更新时间:2023-11-30 01:19:30 25 4
gpt4 key购买 nike

使用其中使用了多个 fragment 的应用程序,并且以下代码用于获取 fragment 的选定位置。

private BaseFragment getSelectedFragment(FragmentManager fragmentManager)
{
int item = getModel().getSelectedItem();//0th position last
String tag = String.valueOf(item);
BaseFragment fragment = (BaseFragment) fragmentManager.findFragmentByTag(tag); //error shown at this line
return fragment;
}

并从

调用上面的方法
public boolean onBackPressed() 
{
FragmentManager fragmentManager = activity.getFragmentManager();
BaseController fragmentController = getSelectedFragment(fragmentManager).getController();
}

由于以下错误而崩溃

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String xxx.android.fwk.app.fragment.BaseFragment.getTag()”。

使用以下代码替换 fragment

private void displaySelectedFragment()
{

FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
// pop any inner fragments that have been added.
fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

// get the selected item position
int selectedItem = model.getSelectedDrawerItem().getItemId();

String tag = String.valueOf(selectedItem);
Bundle extras = model.getExtras();

BaseFragment newFragment = NomadFragmentManager.getInstance().getFragment(selectedItem, extras);
if (newFragment != null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.container, newFragment, tag);
ft.commit();
}
}

那么实际问题的原因是什么?深入研究这段代码。非常感谢任何帮助。提前致谢

最佳答案

引自Document

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

替换 Fragment 会将其从返回堆栈中完全移除。因此,如果您在与其他 Fragment 交易后尝试检索 Tag,则它将不可用。您应该使用以下方法将 Fragment 添加到返回堆栈addToBackStack(tagName)

关于android - Fragment 的 GetTag 返回空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339602/

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