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);
}
}
});
}
}
然後就ok了,很多地都可以用到這個辦法。
源代碼在下面:
http://download.csdn.net/detail/zoeice/4399601