【问题标题】:Trouble triggering onKey event with Android无法使用 Android 触发 onKey 事件
【发布时间】:2010-07-27 05:16:31
【问题描述】:

我无法触发主视图的 onKey 事件。我不确定我做错了什么,我已经正确实现了 onClick 事件,但似乎无法弄清楚 onKey 事件。

以下是相关代码:

public class MyActivity extends Activity {
    private RelativeLayout main;
    private ApplicationToolbar toolbar;

    public void onCreate(Bundle savedInstanceState) {
        ...
        this.main = (RelativeLayout) this.findViewById(R.id.main);
        this.toolbar = new ApplicationToolbar(this);

        //  toolbar is added to main later on in the code...

        this.main.setOnClickListener(mClickListener);
        this.main.setOnKeyListener(mKeyListener);
    }

    private OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View v) {
            toolbar.setVisibility(View.VISIBLE);    // Works correctly.
        }
    };

    private OnKeyListener mKeyListener = new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            toolbar.setBackgroundColor(0xFF0000FF);    //  Does not work.
            return true;
        }
    };
}

事实上,无论我在 mKeyListener 中放置什么代码,它都不会执行,这让我相信事件本身永远不会被触发,即使我按下了物理键盘上的一堆键(Motorola Droid、Android 2.1)。

【问题讨论】:

    标签: java android key listener


    【解决方案1】:

    您可以尝试覆盖onKeyDown(int keyCode, KeyEvent event)

    检查:

    【讨论】:

    • 谢谢,覆盖 onKeyDown 事件有效,对于我的情况,这是一个可行的解决方法。知道为什么我上面的方法不能正常工作吗?
    • @celestialorb:当你按下一个键时,也许你没有任何RelativeLayout 的孩子onFocus。尝试在里面添加EditText
    猜你喜欢
    • 2012-08-19
    • 2013-09-07
    • 2020-09-12
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2011-05-26
    相关资源
    最近更新 更多