Skip to content Skip to sidebar Skip to footer

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,

Solution 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.

publicclassMainActivityextendsFragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protectedvoidonCreate(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
    publicvoidonBackPressed() {
       
        //get current tab index.int index = mTabHost.getCurrentTab();

        //decide what to doif(index!=0){
            mTabHost.setCurrentTab(index-1);
        } else {
            super.onBackPressed();
        }
    }
}

Post a Comment for "Handle Back Press In Tabs With Fragment"