Android中的Space键单击事件

问题描述 投票:0回答:1

我想在Android键盘中获取空格键事件。我尝试了一些来自Google搜索的代码。但没有任何效果。

 public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.KEYCODE_SPACE){
            Toast.makeText(PrabheshActivity.this, "ssss", Toast.LENGTH_SHORT).show();
        }
        return true;
    }

为什么这不起作用?请帮助

android keyevent
1个回答
0
投票

只需尝试将TextWatcher添加为文本输入侦听器,看看是否有空格。检查空格的ASCII码,即32

例如:

private TextWatcher postTextWatcher = new TextWatcher() {

    private int lastLength;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        lastLength = s.length();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        try {
            if (lastLength > s.length()) return;
            if (s.charAt(s.length() - 1) == 32) {
                //32 is ascii code for space, do something when condition is true.
            }
        } catch (IndexOutOfBoundsException ex) {
            //handle the exception
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        //do something
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.