Android ActionBar 选项卡设置初始选定的选项卡 [英] Android ActionBar tabs set initially selected tab
问题描述
我注意到在使用
actionBar.setSelectedNavigationItem(x)
在我的 Activity 的 onCreate() 方法中,始终先选择位置 0 的选项卡项,然后加载位置 x 的选项卡项.这意味着(因为我使用的是 Fragments)2 个 Fragment 被加载.其中之一是不必要的...
in the onCreate() method of my Activity, the tab item at position 0 is always selected first and then the tab item at position x is loaded. This means that (since I'm using Fragments) 2 Fragments are loaded. One of them being unnecessary...
这是我的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Determine which bundle to use; either the saved instance or a bundle
// that has been passed in through an intent.
Bundle bundle = getIntent().getExtras();
if (bundle == null) {
bundle = savedInstanceState;
}
// Initialize members with bundle or default values.
int position;
if (bundle != null) {
position = bundle.getInt("selected_tab");
} else {
position = 0;
}
// Set the tabs.
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar
.newTab()
.setText("Tab 1")
.setTabListener(
new TabListener<RendersGridFragment>(this, "1",
RendersGridFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText("Tab 2")
.setTabListener(
new TabListener<RendersGridFragment>(this, "2",
RendersGridFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText("Tab 3")
.setTabListener(
new TabListener<RendersGridFragment>(this, "3",
RendersGridFragment.class));
actionBar.addTab(tab);
actionBar.setSelectedNavigationItem(position);
}
似乎默认情况下最初选择了位置 0 的选项卡.但是,正如您所看到的,我正在传递包以确保再次运行活动 onCreate() 方法时仍选择了最后选择的选项卡.
It seems that the tab at position 0 is selected initially by default. But, as you can see, I'm passing bundles to make sure the last selected tab is still selected when the activity onCreate() method is run again.
例如,如果最后选择的选项卡在位置 2,则 onCreate() 运行并加载位置为 0 的选项卡,然后加载位置 2 的选项卡.
For example, if the last selected tab is at position 2, the onCreate() runs and the tab at position is 0 is loaded, then the tab at position 2 is loaded.
在使用 actionBar.setSelectedNavigationItem(position) 时,如何确保 ActionBar 不会先选择位置 0 的选项卡.
How can I make sure the ActionBar doesn't select tab at position 0 first when using actionBar.setSelectedNavigationItem(position).
推荐答案
使用其他 addTab
调用来覆盖此行为.您需要先添加要选择的选项卡(在您的情况下,是位置 2 的选项卡).相关Javadoc>
Use the other addTab
calls to override this behaviour. You'll need to add the tab you want to be selected first (in your case, the tab at position 2). Relevant Javadoc
actionBar.addTab(tab2);
actionBar.addTab(tab0, 0, false);
actionBar.addTab(tab1, 1, false);
这篇关于Android ActionBar 选项卡设置初始选定的选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!