I have created the simplest Android project I can in order to test using an OnKeyListener to see what is being typed in an EditText widget. The problem is that the onKey method is only firing for the return key - no others. Based on my code below, what can possibly be preventing the OnKeyListener from working?
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;
}
});
}
}
And the layout file:
<?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>
Once again, the only key press for which I get a log statement is the return key ("keyCode=66"). I have also used breakpoints to confirm that that is the only time that code executes. What could my problem be? Thanks.
You should use TextWatcher instead of 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
}
};
精彩评论