Android read from keyboard

狂风中的少年 提交于 2019-12-06 06:20:31

If you implement onKeyDown() in your Activity and there is no other UI widget that handles key events you should get every key press from your keyboard. Below example should work for A-Z at least and is intended to simply "print" the keypresses to a TextView.

You might need to add a more sophisticated way to map keycode to character if that is not enough. (e.g. space does not work, numbers probably neither)

public class KeyActivity extends Activity {
    // should work for a-z
    private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // there is just a TextView, nothing that handle keys
        mTextView = (TextView) findViewById(R.id.textView1);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        String key = KeyEvent.keyCodeToString(keyCode);
        // key will be something like "KEYCODE_A" - extract the "A"

        // use pattern to convert int keycode to some character
        Matcher matcher = KEYCODE_PATTERN.matcher(key);
        if (matcher.matches()) {
            // append character to textview
            mTextView.append(matcher.group(1));
        }
        // let the default implementation handle the event
        return super.onKeyDown(keyCode, event);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!