Android:Fragment中的后退按钮OnKeyListener不起作用

时间:2017-01-14 06:55:46

标签: android

Fragment中的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;
}

我有什么遗漏的吗?

1 个答案:

答案 0 :(得分:12)

试试这个:

class Button extends React.Component {
    constructor(props, context){
       super(props, context);
       //set local state
     }
    shouldComponentUpdate()  {
        //do some prevalidation
        return result;
    }

   const  myButtonfn = () => {
        //do Something here
    }

    const myButtonfn2 = () => {
        //doSomething else
    }
}

class ButtonBar extends Button {

     constructor(props, context){
       super(props, context);
       //set local state
     }
    shouldComponentUpdate() {
        // No need to bind if you are call super method in ES6
        return myLogic && super.shouldComponentUpdate(); 
    }

    myButtonBarfn = () => {
        //I should be able to do this
        super.myButtonfn();
        super.myButtonfn2();
    }
}