August 15, 2017

How to get onBackPressed() in a Fragment page.

                                               
                                                  In this Blog I am going to explain how to trigger Back button press (onBackPressed() method) event on my fragment page.  I am doing this with the help of  an "interface" in java. For this I am creating an Activity Class and a Fragment Class. 


HomeScreen (Activity Class)


      In this class we created an interface "OnBackPressedListener" to detect the back press.  When  it execute onBackPressed() event it will execute the interface method "doBack()" which will trigger the event on the Fragment page.



public class HomeScreen extends Activity {

    protected OnBackPressedListener onBackPressedListener;

    public interface OnBackPressedListener {
        void doBack();
    }

    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);

    }


    @Override
    public void onBackPressed() {
        if (onBackPressedListener != null)
            onBackPressedListener.doBack();   
    }

}


MyFragment (Fragment Class)

    In this Class it will automatically create the override method "doBack()" while we implements "HomeScreen.OnBackPressedListener" with the fragment page. Also we need to initialize the interface on "onCreateView" of the fragment page to get the event notification about "onBackPressed()".



public class MyFragment extends Fragment implements HomeScreen.OnBackPressedListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout.fragment_profile, container, false);

          ((HomeScreen) getActivity()).setOnBackPressedListener(this);

    }


    @Override
    public void doBack() {
          //Here Comes your Code
    } 

}