2
有人會好心建議爲什麼OnKey()方法中的代碼沒有執行。請注意,我試圖觸發這個,我點擊了android鍵盤上的「搜索」按鈕。OnKeyListener()沒有執行
下面是主要代碼:
package com.onkeyexample1;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
public class OnKeyExample1Activity extends Activity {
EditText editText;
OnKeyListener onKeyListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnKeyListener(onKeyListener);
editText.addTextChangedListener(inputTextWatcher);
onKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
System.out.println("Clicked");
return true;
}
};
}
我嘗試添加以下代碼塊作爲建議的修復,但它並沒有幫助:
private TextWatcher inputTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{ }
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Log.d(TAG, s.charAt(count-1) + " character to send");;
}
};
}
這裏是我的佈局XML:
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText android:imeOptions="actionSearch" android:layout_width="fill_parent"
android:id="@+id/editText1" android:layout_height="wrap_content">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
任何建議,非常感謝!
這是第一個實現Ted的暗示:
public class OnKeyExample1Activity extends Activity {
EditText editText;
OnKeyListener onKeyListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnKeyListener(onKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
System.out.println("Clicked");
return true;
}
});
}
}
這裏的修復程序在我的評論中提到的雙觸發問題:
editText.setOnKeyListener(onKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
System.out.println("Argh");
return false;
}
return true;
}
});
}
特德,謝謝你的建議,它現在只工作,現在看來我的代碼在onKey()正在執行兩次。能想到這個的任何原因嗎? 再次非常感謝您的幫助。 – Ben
特德,解決了雙重觸發問題(請參閱我上面的代碼)。再次感謝您的幫助! – Ben