我有一个EditText,我尝试从我的dispatchKeyEvent
拨打Activity
,将文字插入EditText
,如下所示:
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));
}
}
}
字母工作正常,但KeyEvents
移位和大写字母无效。上面的代码将“lol”写入EditText
而不是“Lol”,这是预期的。为什么呢?
答案 0 :(得分:0)
您可以使用另一个KeyEvent()构造函数来使用移位元数据,如下所示:
dispatchKeyEvent(new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_L,0,KeyEvent.META_SHIFT_ON));
来源:https://developer.android.com/reference/android/view/KeyEvent.html