本文介绍了dispatchKeyEvent()调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调试下面的代码片断和谙 dispatchKeyEvent()被调用两次方法。请建议的解决方案

  @覆盖
公共布尔dispatchKeyEvent(KeyEvent的事件){
如果(event.getKey code()== KeyEvent.KEY code_DPAD_CENTER)
    {
        如果(cDetail.getVisibility()== View.VISIBLE)
        {            cDetail.setVisibility(View.INVISIBLE);
            cList.setVisibility(View.INVISIBLE);
        }        其他
        {            cDetail.setVisibility(View.VISIBLE);
            cList.setVisibility(View.VISIBLE);        }
    }    返回super.dispatchKeyEvent(事件);
}


解决方案

dispatchKeyEvent火两次:第一次键不放,并为关键了第二次,所以你必须进行过滤:

 如果(event.getAction()!= KeyEvent.ACTION_DOWN)
                返回true;            开关(键code){
            案例KeyEvent.KEY code_1:
                MakeToast(1);
                打破;
            案例KeyEvent.KEY code_2:
                MakeToast(2);
                打破;
            案例KeyEvent.KEY code_3:
                MakeToast(3);
                打破;            }

I debugged the following snippet and come to know the method dispatchKeyEvent() is invoked twice. please suggest the solution

    @Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode()== KeyEvent.KEYCODE_DPAD_CENTER)
    {
        if(cDetail.getVisibility()==View.VISIBLE  )
        {

            cDetail.setVisibility(View.INVISIBLE);
            cList.setVisibility(View.INVISIBLE);
        }

        else
        {

            cDetail.setVisibility(View.VISIBLE);
            cList.setVisibility(View.VISIBLE);

        }


    }

    return super.dispatchKeyEvent(event);
}
解决方案

dispatchKeyEvent fire twice: the first time for key down, and the second time for key up, so you have to filter:

 if (event.getAction()!=KeyEvent.ACTION_DOWN)
                return true;

            switch (keyCode) {
            case KeyEvent.KEYCODE_1 :
                MakeToast(1);
                break;
            case KeyEvent.KEYCODE_2 :
                MakeToast(2);
                break;
            case KeyEvent.KEYCODE_3 :
                MakeToast(3);
                break;

            }

这篇关于dispatchKeyEvent()调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 09:42