Saturday, October 5, 2019

How to Handle Fragment from Main Activity backpress


MainActivity.java

public interface OnBackPressedListner{
    boolean onBackPressed();
}



@Overridepublic void onBackPressed() {


Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mainContent);
if(!(fragment instanceof  OnBackPressedListner)|| !((OnBackPressedListner)fragment).onBackPressed()){

    Toast.makeText(this, "back", Toast.LENGTH_SHORT).show();
    setTitle("HSC ICT");
   super.onBackPressed();
}else {

    if (doubleBackToExitPressedOnce) {
        finish();
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override        public void run() {
            doubleBackToExitPressedOnce=false;
        }
    }, 2000);



   // Toast.makeText(this, "new ", Toast.LENGTH_SHORT).show();}

}




In Fragment :-

public class FirstChapter extends Fragment implements MainActivity.OnBackPressedListner 
{


@Overridepublic boolean onBackPressed() {
    Toast.makeText(getContext(), "Back Click", Toast.LENGTH_SHORT).show();
    return false;
}


}




Easily handle Fragment from Activity.