2011-08-29 80 views
2

我已經創建了最簡單的Android項目,我可以使用OnKeyListener來測試EditText小部件中正在鍵入的內容。問題在於onKey方法只爲返回鍵觸發 - 沒有其他方法。根據我的代碼,可能會阻止OnKeyListener的工作?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> 

再次,唯一的按鍵,對此我得到一個日誌語句是返回鍵(「鍵代碼= 66」)。我還使用斷點來確認這是代碼執行的唯一時間。我的問題是什麼?謝謝。

回答

6

您應該使用的,而不是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 
     } 
}; 
+0

燁TextWatcher,我已經走了這條路走了。 –

+1

那是因爲OnKeyListener沒有註冊字符鍵?該文件似乎表明它監聽任何按鍵。 –