本文介绍了findFragmentByTag()始终返回null-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我有一个主要活动和几个片段.当用户单击后退按钮时,片段将一一弹出.我想确定当前在后堆栈中的哪个片段.因此,用于通过片段标签名称识别片段.我使用以下代码段获取片段标签名称,但始终返回空值.
In my application i have one main activity and several fragments. when user click the back button fragments pops one by one. I want to identify which fragment currently in the back stack. So use to identify fragments by fragment tag name. i used following code segment to get fragment tag name but it always returns null value.
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String fragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();
请帮助.
编辑
用标签替换片段
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
推荐答案
我发现了我的错误,是我忘记了将TAG添加到堆栈中.
i found my mistake, it is i forgot to add TAG to back stack.
FragmentManager fm = mainActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
ft.addToBackStack(text);
然后我可以按如下方式获取当前的片段TAG名称,
And then i can get the current fragment TAG name as follows,
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String currentFragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();
这篇关于findFragmentByTag()始终返回null-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!