How to catch key events while soft keyboard is open android?

落爺英雄遲暮 提交于 2019-12-24 20:13:56

问题


I know how to catch key events in my activity by overriding

public boolean onKeyDown(int keyCode, KeyEvent event)

The problem is when the soft keyboard is open this method is not even called... any way to catch the event anyway?


回答1:


Yes, when we speak about soft keyboard it's means that no so easy to use it. By the way methods that relate to soft keyboard take no expected result. For example:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    //do something
    return super.onKeyDown(keyCode, event);
}

The workaround that I've found is using of TextWatcher. Use this code for your application

YourEdit = (EditText) findViewById(R.id.YourEdit);         
YourEdit.addTextChangedListener(new TextWatcher()
{
        public void  afterTextChanged (Editable s)
        { 
            //checking of TextWatcher functionality
            Toast.makeText(mContext, "afterTextChanged", 3).show();    
            //do something
        } 

        public void  beforeTextChanged  (CharSequence s, int start, int count, int after)
        { 
            //checking of TextWatcher functionality
            Toast.makeText(mContext, "beforeTextChanged", 3).show();    
            //do something
        } 

        public void  onTextChanged  (CharSequence s, int start, int before, int count) 
        { 
            //checking of TextWatcher functionality
            Toast.makeText(mContext, "onTextChanged", 3).show();    
            //do something
        }
});

These methods are called sequentially: beforeTextChanged, onTextChanged and afterTextChanged. You can catch any phase of text changing. Good luck!



来源:https://stackoverflow.com/questions/6883334/how-to-catch-key-events-while-soft-keyboard-is-open-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!