如何在android中获取backstack片段条目列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12015393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a list of backstack fragment entries in android?
提问by Harshal Kshatriya
I'm working on an application in which tabs are implemented using FragmentActivity
. Since, tabs are required throughout the application, fragments are used extensively to make the application compatible on all the versions of android.
我正在开发一个应用程序,其中使用FragmentActivity
. 由于整个应用程序都需要选项卡,因此广泛使用片段来使应用程序与所有版本的 android 兼容。
As a consequence, I'm facing a problem in visualizing as to what fragments are present on the backstack. I'm sure there is a way to retrieve the list of fragments present on the backstack. Thanks.
因此,我在可视化 backstack 上存在哪些片段时遇到了问题。我确信有一种方法可以检索 backstack 上存在的片段列表。谢谢。
回答by Error 454
The FragmentManagerhas methods:
该FragmentManager有一些方法:
getBackStackEntryCount()
getBackStackEntryCount()
getBackStackEntryAt (int index)
getBackStackEntryAt(整数索引)
FragmentManager fm = getFragmentManager();
for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
Log.i(TAG, "Found fragment: " + fm.getBackStackEntryAt(entry).getId());
}
回答by Harsh Mittal
If you want to check which fragment is visible and if you know the id of view where fragment is placed, first you have to add below in onCreate()
如果您想检查哪个片段是可见的,并且您知道放置片段的视图的 id,首先您必须在 onCreate() 中添加以下内容
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
if (f != null){
updateActionBarTitle(f);
}
}
});
private void updateActionBarTitle(Fragment fragment) {
String fragClassName = fragment.getClass().getName();
if (fragClassName.equals(FirstFragment.class.getName())) {
setTitle("Home");
} else if (fragClassName.equals(SecondFragment.class.getName())) {
setTitle("Second");
}
}
This will update your action bar title on back stack change listener.
这将在返回堆栈更改侦听器上更新您的操作栏标题。