Bhargavi Yamanuri Bhargavi Yamanuri - 6 months ago 55
Android Question

3 tabs with each one carry 1 fragment and when press back go to previous tab

I want to create 3 tabs and each one have single fragment,when i press back button in device instead of closing of app i need to go previous tab.I had try a lot but not find correct answer which is suitable for my app.I am new to development.

What i have in my project is 3 tabs when i am at tab 3 if i press it needs to go tab 2 instead of closing app.

What ever suggestions i get those are helped only go back to previous fragment.
But i want go to previous tab when we press back button in android device.


If you have different fragments in one tab if you press back button by using OnBackPressed() we can go for previous fragment.For that situation following code will help you.

public void On BackPressed(){
//You can check by write toast if it working are not.
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
    // If there are back-stack entries, leave the FragmentActivity
    // implementation take care of them.
    //implement your code here.


It will help you to go back of your previous fragments not previous tabs.

this will help you understand. Separate Back Stack for each tab in Android using Fragments