向后压入带有碎片的标签 [英] Handle back press in tabs with fragment
问题描述
我在我的应用程序中使用FragmentTabHost.我有三个标签.每个选项卡都显示一个片段.
I am using FragmentTabHost in my app. I have three tabs. Each tab shows a Fragment.
addTab("Tab1", R.drawable.ic_launcher, Fragment1.class);
addTab("Tab2", R.drawable.ic_launcher, Fragment2.class);
addTab("Tab3", R.drawable.ic_launcher, Fragment3.class);
addTab("Tab3", R.drawable.ic_launcher, Fragment4.class);
当我从这些选项卡中的任意一个按回来时,该应用程序将关闭并显示主屏幕.现在我想要的是,当我从Tab1按下时,该应用程序应该关闭.但是,如果我从Tab2或Tab3中按回去,则应该将用户发送到Tab1.摘要是:
When I press back from any of these tabs, the app is closed and home screen is shown. Now what I want is, when I press back from Tab1, the app should close. However, if I press back from Tab2 or Tab3, the user should be sent to Tab1. Summary is:
当前在Tab1中->回退->应用关闭
Currently in Tab1 -> press back -> app close
当前在Tab2中->向后按->转到Tab1
Currently in Tab2 -> press back -> Go to Tab1
当前在Tab3中->回退->转到Tab1
Currently in Tab3 -> press back -> Go to Tab1
我该如何实现?
推荐答案
在您的Activity(拥有FragmentTabHost的位置)中,覆盖onBackPressed()
.在onBackPressed()中,您可以检查currentTab的位置.
In your Activity (where you have your FragmentTabHost) override the onBackPressed()
. In onBackPressed() you can check for the currentTab's position.
如果当前标签页不为0(即不是第一个标签页),则然后将上一个标签页设置为当前标签页.
If current tab is not 0 (i.e. not the first tab) then set the previous tab as the current tab.
否则当前标签为0,则退出该应用.
Else if current tab is 0, exit the app.
由于我没有您的实际课程,所以我用FragmentTabHost
创建了一个虚拟课程,只是为了演示如何实现.
Since i do not have your actual class, I created a dummy class with FragmentTabHost
just to demonstrate how it can be done.
public class MainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(R.id.tab_host);
mTabHost.setup(this, getSupportFragmentManager(), R.id.tab_framelayout);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("Tab1",
getResources().getDrawable(R.drawable.ic_launcher)),
Fragment1.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Tab2",
getResources().getDrawable(R.drawable.ic_launcher)),
Fragment2.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("Tab3",
getResources().getDrawable(R.drawable.ic_launcher)),
Fragment3.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab4").setIndicator("Tab4",
getResources().getDrawable(R.drawable.ic_launcher)),
Fragment4.class, null);
}
@Override
public void onBackPressed() {
//get current tab index.
int index = mTabHost.getCurrentTab();
//decide what to do
if(index!=0){
mTabHost.setCurrentTab(index-1);
} else {
super.onBackPressed();
}
}
}
这篇关于向后压入带有碎片的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!