標籤:
android中的編輯框EditText也比較常用,那比如在搜尋方塊中,沒輸入一個字,下面的搜尋列表就顯示有包含輸入關鍵字的選項,這個輸入監聽怎麼實現的呢?
我們可以建一個例子,如下:
我們可以監聽游標處在哪個位置,選擇了幾個字元並處理,輸入了幾個字元
先建立布局檔案
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/af"> <!-- 上下滾動 --> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- 編輯框 --> <EditText android:id="@+id/id_edittext_1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/alert_light" android:textSize="10sp" android:textColor="#ffff" /> <TextView android:id="@+id/id_textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#ffff" /> <TextView android:id="@+id/id_textview_1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/hah" android:textColor="#f000" /> <TextView android:id="@+id/id_textview_2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/hah" android:textColor="#f000" /> </LinearLayout> </ScrollView></LinearLayout>
然後在代碼中對編輯框綁定輸入監聽事件:
public class EditTextTestActivity extends Activity { /**編輯框*/ private EditText edit1_; /**文本*/ private TextView text_; private TextView text1_; private TextView text2_; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /*設定當前頁面的布局*/ setMyLayout(); } /** * 設定當前頁面的布局 */ private void setMyLayout(){ /*取得文本*/ text_ = (TextView)findViewById(R.id.id_textview); text1_ = (TextView)findViewById(R.id.id_textview_1); text2_ = (TextView)findViewById(R.id.id_textview_2); /*取得編輯框*/ edit1_ = (EditText)findViewById(R.id.id_edittext_1); /*監聽 編輯框中的文本改變事件*/ edit1_.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /*++ 文本每次改變就會跑這個方法 ++*/ if(null != text_){ text_.setText("您正在輸入......\n當前游標處在第 " + start +" 個位置\n您選擇處理了 " + before + " 個字元\n您這次輸入的詞語有 " + count + " 個字元"); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { /*++這裡的count樹枝上是和onTextChanged()裡的before一樣的 * after樹枝上是和onTextChanged()裡的count一樣的 ++*/ if(null != text1_){ text1_.setText("您正在輸入......\n當前游標處在第 " + start +" 個位置\n您選擇處理了 " + count + " 個字元\n您這次輸入的詞語有 " + after + " 個字元"); } } @Override public void afterTextChanged(Editable s) { /*++這裡顯示出輸入的字串++*/ if(null != text2_){ text2_.setText(s); } } }); }}
原始碼:http://download.csdn.net/detail/zoeice/4399601
Android 監聽EditView中的文本改變事件