片段中的onKeyListener()现在不起作用.这是代码的一部分.
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, null); ... view.setFocusableInTouchMode(true); view.requestFocus(); view.setOnKeyListener(new View.OnKeyListener() { // true if the listener has consumed the event, false otherwise. // the key event happens twice, when pressing and taking off. @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && !touched) { Log.i(TAG, "onKey() method"); touched = true; return true; } else { return false; } } }); return view; }
有什么我想念的吗?
试试这个:
@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; } }); }