Android dispatchKeyEvent 不适用于所有 KeyEvent 代码

Android dispatchKeyEvent not working for all KeyEvent codes

我有一个 EditText,我尝试从我的 Activity 调用 dispatchKeyEvent 以将文本插入 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 shift 和 capslock 什么都不做。上面的代码将 "lol" 写入 EditText 而不是预期的 "Lol" 。为什么?

您可以使用 KeyEvent() 的另一个构造函数来使用 shift 元数据,如下所示:

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