android - OnKeyListener仅检测返回键

标签 android android-edittext

我已经创建了最简单的 Android 项目,以便使用 OnKeyListener 进行测试,以查看在 EditText 小部件中键入的内容。问题是 onKey 方法仅针对返回键触发 - 没有其他方法。根据我下面的代码,什么可能阻止 OnKeyListener 工作?

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setViewListeners();
    }

    private void setViewListeners() {

        EditText et1 = (EditText)findViewById(R.id.text1);          
        EditText et2 = (EditText)findViewById(R.id.text2);

        et1.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("INFO", "keyCode=" + keyCode);
                return false;
            }
        });
     }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
          android:id="@+id/text1"   
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          />
    <Spinner 
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        />
    <EditText 
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

再一次,我得到日志语句的唯一按键是返回键(“keyCode=66”)。我还使用断点来确认这是代码执行的唯一时间。我的问题可能是什么?谢谢。

最佳答案

您应该使用 TextWatcher 而不是 OnClickListener

mPostEditText.addTextChangedListener(watcher);

TextWatcher watcher = new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
        // TODO Auto-generated method stub
        }
    }
        @Override
    public void beforeTextChanged(CharSequence charsequence, int i, int j,  int k) {
        // TODO Auto-generated method stub
        }
        @Override
    public void afterTextChanged(Editable editable) {
        // TODO Auto-generated method stub
        }
};

关于android - OnKeyListener仅检测返回键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7232398/

相关文章:

更改类文件后 Android 上出现 java.lang.NoClassDefFoundError

android - 在 Android 4.x 上按下时 Listview 中的 EditText 失去焦点

android - 背景大小 : auto not working as expected on android 6

android - RxJava 运算符类似于 replay(1, 1, MINUTE),但在 1 分钟后重新订阅

java - Gradle绝对/相对路径

android - 如何在Edittext中添加Change listener

android - 在android中的edittext中插入textview?

android - 默认 EditText 填充的值是多少?

android - 如何让EditText只能读取和复制但不能编辑

android - 将连续语音识别添加到我的 Android 应用程序