I have an EditText and I try to call dispatchKeyEvent
from my Activity
to insert text into the EditText
like so:
public class MainActivity extends AppCompatActivity implements View.OnFocusChangeListener {
String TAG = "test";
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: ");
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edittext);
editText.setOnFocusChangeListener(this);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d(TAG, "onFocusChange: "+hasFocus);
if(hasFocus) {
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_L));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_O));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_L));
}
}
}
Letters work fine but KeyEvents
for shift and capslock do nothing. The above code writes "lol" to the EditText
instead of "Lol" which would be expected. Why?
You can use another Constructor of KeyEvent() to use shift metadata like this:
dispatchKeyEvent(new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_L,0,KeyEvent.META_SHIFT_ON));
Source : https://developer.android.com/reference/android/view/KeyEvent.html