Catching key pressed with the virtual keyboard in

2019-03-25 07:20发布

问题:

With the physical keyboard you can catch key presses with a KeyListener, something like:

myEditText.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) { 
            /* do something */ 
        }
    }
});

Does anyone know how to do this (or similar) with the virtual keyboard?

回答1:

So far i haven't found any listener for the virtual keypad in android. I found an alternate solution i.e. i used the TextChanged event to retrieve the value of the keys entered in the Edit Text.

import android.app.Activity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.view.View.OnKeyListener;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class ShowKeypad extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
            EditText emailTxt = (EditText) findViewById(R.id.editText);

            emailTxt.addTextChangedListener(new TextWatcher()
            {
                    public void  afterTextChanged (Editable s){ 
                            Log.d("seachScreen", "afterTextChanged"); 
                    } 
                    public void  beforeTextChanged  (CharSequence s, int start, int 
                            count, int after)
                    { 
                            Log.d("seachScreen", "beforeTextChanged"); 
                    } 
                    public void  onTextChanged  (CharSequence s, int start, int before, 
                            int count) 
                    { 
                            Log.d("seachScreen", s.toString()); 
                    }

            final TextView tv = (TextView)findViewById(R.id.tv);
    }); 
    }

}