简体   繁体   中英

How to disable back button pressed in android fragment class

I want to disable the back button in a fragment class. onBackPressed() doesn't seem to work in this fragment. How could I disable the back button?

This is my sample code:

public class Login extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
       ,Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login, null);
        return root;
    }

    public void onBackPressed() {
    }
}

You have to override onBackPressed of parent FragmentActivity class. Therefore, put your codes in parent FragmentActivity. Or you can call parent's method by using this:

public void callParentMethod(){
    getActivity().onBackPressed();
}

in FragmentActivity override onBackPressed Method and not call its super class to disable back button.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity:

    // Disable onBack click
    requireActivity().onBackPressedDispatcher.addCallback(this) {
      // With blank your fragment BackPressed will be disabled.
    }

Here is the android doc link: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

In your parent Activity

@Override
public void onBackPressed() {

    Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
    if (f instanceof yourfragment) {//the fragment on which you want to handle your back press
        Log.i("BACK PRESSED", "BACK PRESSED");
    }else{
        super.onBackPressed();
    }
}

In your oncreateView() method you need to write this code and in KEYCODE_BACk return should true then it will stop the back button option for particular fragment

     View v = inflater.inflate(R.layout.xyz, container, false);
    //Back pressed Logic for fragment  
    v.setFocusableInTouchMode(true);  
    v.requestFocus();  
    v.setOnKeyListener(new View.OnKeyListener() {  
    @Override  
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {

                return true;  
            }  
        }  
        return false;  
    }  
});

OnBackPressedCallback

Here is the code which you can write in your Fragment class to customize the back button press.

public class MyFragment extends Fragment{

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
            @Override
            public void handleOnBackPressed() {
                // Handle the back button even
                Log.d("BACKBUTTON", "Back button clicks");
            }
        };

        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

     }

}

Relevant link

You can read and research more on this HERE

I know it's too late, In fragment onCreate

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
Log.d("tag","back button pressed")    // Handle the back button event
}

callback.isEnabled

Change

public void onBackPressed() {
}

to

@Override
public void onBackPressed() {
    super.onBackPressed()
}

OR

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

    }
    return super.onKeyDown(keyCode, event);    
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

    onBackPressed();
}

return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {

return;
}

if you want to fragment never closed without any button action you can try to prevent cancel Fragment.

In your fragment method add this

 this.setCancelable(false);

Just override onBackPressed in your fragment where you want to disable the back press.

More info here: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

public class Login extends Fragment {
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // Log.d("TAG", "Pressed...");
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    }
}

I know it's too late but maybe this code helps someone works with kotlin.

  • in the activity which contains your fragment override onBackPressed Function.

  • check if your frameLayout Which will have the fragment is empty.

  • if the container is empty, super.onBackPressed will call.

     override fun onBackPressed() { val frameLayout = supportFragmentManager.findFragmentById(R.id.yourFrameLayout) if (frameLayout == null) { super.onBackPressed() } }

只需放置一个透明视图并为其设置 onClickListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM