2013-07-19 200 views
8

我想禁用片段類中的後退按鈕。 onBackpressed無法在fragment.how中禁用後退按鈕? 這是我的簡單代碼。如何禁用在Android片段類中按下後退按鈕

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

for fragment popbackstack()方法用於.. –

回答

12

你必須覆蓋父FragmentActivity類的onBackPressed。因此,把你的代碼放在父FragmentActivity中。或者,您可以通過使用此調用父的方法:

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

在FragmentActivity覆蓋onBackPressed方法,而不是調用父類禁用後退按鈕。

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

其工作正常謝謝你 – JellyBean

3

變化

public void onBackPressed() { 
    } 

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

在你父活動

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

在你oncreateView()方法中,你需要編寫代碼,並在KEYCODE_BACk回報應真,那麼它將停止針對特定片段後退按鈕選項

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