大部分文章介紹的禁用返回鍵方法都只適用於Activity:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
然後Fragment的資料比較少而且看起來都有夠麻煩XD
但是今天爬到這個文!有夠快速有夠簡單!(喜極而泣)
需要注意的是這不是onCreateView!!
直接放在class就可以啦
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().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) {
//go to previous fragemnt
//perform your fragment transaction here
//pass data as arguments
return true;
}
}
return false;
}
});
}
來源:https://stackoverflow.com/questions/41647583/android-back-button-onkeylistener-inside-fragment-is-not-working