-5

I am using an activtity in which it is placed by fragment A. fragment A contains 3 tabs tab A, tab B and tab C on app launches the tab B is shown. These 3 tabs have a list when any of the list is clicked the fragment A is replaced by fragment B, when backpressed from fragment B it should show the tab from which it have been clicked.

sschrass
  • 7,014
  • 6
  • 43
  • 62
kumaresan
  • 27
  • 7
  • 2
    Welcome to Stack Overflow! Please take a moment to read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Teasel Nov 30 '17 at 07:30
  • 2
    Can you post what you've tried so far ? – Ionut J. Bejan Nov 30 '17 at 07:30

2 Answers2

0

Follow this. Its awesome example to implement onBackPressed() functionality on Fragment by using Abstract Class and Backable Fragment.

1) Create an Abstract Class -

import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public abstract class BackableFragment extends Fragment implements View.OnKeyListener {

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(this);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                onBackButtonPressed();
                return true;
            }
        }

        return false;
    }

    public abstract void onBackButtonPressed();
}

2) Implement the Abstract Class to your Fragment -

public class FragmentChannels extends BackableFragment {

    ...

    @Override
    public void onBackButtonPressed() {
        if (doTheThingRequiringBackButtonOverride) {
            // do the thing
        } else {
            //go to your preferable fragment or activity when you press back on any fragment  
        }
    }

    ...
}

Thats it. Reference

AGM Tazim
  • 2,213
  • 3
  • 16
  • 25
0
Try this in on click 

view = getActivity().findViewById(R.id.activity_page1);
                ViewPager viewPager= (ViewPager)view.findViewById(R.id.viewpager);
                int tab = viewPager.getCurrentItem();
                tab--;
                viewPager.setCurrentItem(tab);
Jyoti Sharma
  • 233
  • 1
  • 9