下面的例子实现了两个编辑框的事件监听,当编辑相应编辑框时上面的文本框
就会显示当前状态。
第一个编辑框接受拨号键盘的输入,包括数字和一些字符,这些字符有( ) # * / ; - + , . 这10个,
不知道还有没有其他的,第二个接受密码输入,输入的字符将被显示成一个点。
代码:
package com.th;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取布局文件中的编辑框
final EditText ET_phone = (EditText)findViewById(R.id.ET_phonenumber);
EditText ET_password = (EditText)findViewById(R.id.ET_password);
//获取布局文件中的文本框
final TextView text = (TextView)findViewById(R.id.myTextView);
//为手机号文本框添加监视器
ET_phone.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
text.setText("Editing ET_phonenumber"); //当 ET_phone 改变时,修改文本框内容
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
ET_password.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
text.setText("Editing ET_password");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
布局文件:
<!-- main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入手机号和密码"/>
<EditText
android:id="@+id/ET_phonenumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLength="40"
android:hint="Please enter your phone"
android:textColorHint="#FF000000"
android:phoneNumber="true">
<!-- 获得焦点 -->
<requestFocus />
</EditText>
<EditText
android:id="@+id/ET_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLength="40"
android:hint="Please enter your password"
android:password="true"
android:textColorHint="#FF000000"/>
</LinearLayout>