Handle back press in tabs with fragment

大憨熊 提交于 2019-12-13 08:38:06

问题


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);

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:

Currently in Tab1 -> press back -> app close

Currently in Tab2 -> press back -> Go to Tab1

Currently in Tab3 -> press back -> Go to Tab1

How can I achieve this?


回答1:


In your Activity (where you have your FragmentTabHost) override the onBackPressed(). In onBackPressed() you can check for the currentTab's position.

If current tab is not 0 (i.e. not the first tab) then set the previous tab as the current tab.

Else if current tab is 0, exit the app.

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();
        }
    }
}


来源:https://stackoverflow.com/questions/25201471/handle-back-press-in-tabs-with-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!