Android setOnEditorActionListener() 不触发

2022-09-04 07:25:33

我正在尝试将侦听器设置为何时按下Enter按钮。但它根本没有开火。我在LG Nexus 4和Android 4.2.2上进行了测试。 适用于Android 2.3的Amazon Kindle Fire,无处可用!我也无法为按钮设置文本。下面是代码:EditTextsetOnEditorActionListenersetImeActionLabelEnter

mEditText.setImeActionLabel("Reply", EditorInfo.IME_ACTION_UNSPECIFIED);
mEditText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            Log.d("TEST RESPONSE", "Action ID = " + actionId + "KeyEvent = " + event);
            return true;
        }  
    });

我做错了什么?我该如何解决这个问题?


答案 1

您可以使用 TextWatcher

editText.addTextChangedListener(new TextWatcher() {
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
        
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
        
    @Override
    public void afterTextChanged(Editable s) {
        if (s.charAt(s.length() - 1) == '\n') {
              Log.d("TAG", "Enter was pressed");
        }
    }
});

答案 2

确保在布局文件中设置了IME_ACTION:

<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

有关完整说明,请参阅 http://developer.android.com/guide/topics/ui/controls/text.html


推荐