简体   繁体   中英

Handle back press in tabs with fragment

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM