editText的onKey事件未触发

时间:2015-07-18 00:41:12

标签: android android-edittext

我很难在我的EditText视图上触发OnKey事件。我已经谷歌搜索超过一个小时了,似乎每个人都说你要做的就是在视图中添加一个OnKeyListener,但它不会触发它。我尝试将它添加到整个Activity中,并尝试将其添加到视图本身,但两种方式都不会触发该函数。

我的代码:

XML:

 <EditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/interests_editText" />

Java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_post);

    interests_editText = (EditText) findViewById(R.id.interests_editText);
    interests_editText.setOnKeyListener(new OnKeyListener(){

               public boolean onKey(    View view,    int keyCode,    KeyEvent event){
                   Log.i("DEBUG","TeST");
                   if (keyCode == KeyEvent.KEYCODE_ENTER) {

                       return true;
                   }
                   else {
                       return false;
                   }
               }
           }
    );

更新 我的最终目标是让它识别你在editText视图中按空格的时间。我添加到XML

android:inputType="text"

然后将代码更改为

public boolean onKey(    View view,    int keyCode,    KeyEvent event){
                   Log.i("DEBUG","Outside");
                   if (keyCode == KeyEvent.KEYCODE_SPACE) {
                       Log.i("DEBUG","Space");
                       return true;
                   }
                   else {
                       return false;
                   }

现在键盘显示一个Next按钮,当按下时会记录“Outside”,但它不会记录“Space”

2 个答案:

答案 0 :(得分:1)

你想捕获Enter事件吗?如果是,请尝试{ "total": 800, "rows": [ { "id": 30, "name": "Item 30", "price": "$30" }, { "id": 31, "name": "Item 31", "price": "$31" }, { "id": 32, "name": "Item 32", "price": "$32" }, { "id": 33, "name": "Item 33", "price": "$33" }, { "id": 34, "name": "Item 34", "price": "$34" }, { "id": 35, "name": "Item 35", "price": "$35" }, { "id": 36, "name": "Item 36", "price": "$36" }, { "id": 37, "name": "Item 37", "price": "$37" }, { "id": 38, "name": "Item 38", "price": "$38" }, { "id": 39, "name": "Item 39", "price": "$39" } ] }

对于您的更新信息:捕获空间键,请尝试setOnEditorActionListener

答案 1 :(得分:0)

跟进@ BNK的回答我使用以下代码让它工作:

interests_editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {

    String str = s.toString();
    if(str.substring(str.length()-1, str.length()).equals(" "))
        Log.i("DEBUG","Space pressed");
    else if(str.substring(str.length()-1, str.length()).equals("\n"))
        Log.i("DEBUG", "Enter pressed");
    else
        Log.i("DEBUG", "Pressed : " +str.substring(str.length()-1, str.length()) );
}}