Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Back Button press from fragment

My application has an activity with so many fragments. I want to disable the back button press in some fragment. I tried with the below code. But it doesn't work.

In the main activity:

@Override
public void onBackPressed() {
        super.onBackPressed();
        OrderFragment.onBackPress();
}

In the fragment,

public static void onBackPressed()
{
    Log.d(TAG,"It listen");
}

I have the log message but, how can I disable the back button from my fragment.

like image 985
Zaw Myo Htet Avatar asked Nov 28 '22 11:11

Zaw Myo Htet


2 Answers

You should keep a reference to the fragment you want to disable/handle back press event on your main activity:

class MainActivity{

    OrderFragment mOrderFragment;

    @Override
    public void onBackPressed() {
        if(mOrderFragment.isVisible())
            mOrderFragment.onBackPressed();
        else
            super.onBackPressed();
    }

}

In OrderFragment:

public void onBackPressed() {
    //handle back press event
}
like image 92
Rey Pham Avatar answered Dec 16 '22 01:12

Rey Pham


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;   
}    
});
like image 20
Raj Kumar Avatar answered Dec 16 '22 02:12

Raj Kumar