如何禁用在Android片段类中按下后退button

我想禁用片段类中的后退button。 onBackpressed无法在fragment.how中禁用后退button?..这是我的简单代码。

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() { } } 

Solutions Collecting From Web of "如何禁用在Android片段类中按下后退button"

你必须重写父FragmentActivity类的onBackPressed。 因此,把你的代码放在父FragmentActivity中。 或者你可以使用这个方法调用父类的方法:

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

在FragmentActivity覆盖onBackPressed方法,而不是调用它的超类禁用后退button。

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

更改

 public void onBackPressed() { } 

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

要么

 @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; } 

在你的oncreateView()方法中,你需要编写这段代码,并在KEYCODE_BACk中返回true,那么它将停止特定片段的后退button选项

  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; } }); 

在你的父母活动

 @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(); } }