给EditText设置addTextChangedListener监听事件就可以实现实时改变文本的个数,代码如下:
首先是布局代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
>
<EditText
android:maxLength="10"
android:layout_centerVertical="true"
android:id="@+id/et_context"
android:layout_width="match_parent"
android:background="@null"
android:layout_height="wrap_content"
android:hint="输入内容" />
<TextView
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/tv_gs2"
android:id="@+id/tv_gs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"/>
<TextView
android:layout_centerVertical="true"
android:id="@+id/tv_gs2"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/10"/>
</RelativeLayout>
布局代码写完后,然后就可以主Activity里写EditText的监听事件:
首先获取到需要用到的控件:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
et_context = (EditText) findViewById(R.id.et_context);
tv_gs = (TextView) findViewById(R.id.tv_gs);
et_context.addTextChangedListener(mTextWatcher); //设置监听
}
然后设置监听:
TextWatcher mTextWatcher = new TextWatcher() {
private CharSequence temp;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Log.d("tag", "beforeTextChanged="+s.toString()+start+count+after);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Log.d("tag", "onTextChanged="+s.toString()+start+before+count);
temp = s;
}
@Override
public void afterTextChanged(Editable s) {
// Log.d("tag", "afterTextChanged = " + s.toString());
tv_gs.setText(temp.length()+"");
}
};
这样一个文本输入框的监听就写完了,afterTextChanged这个方法里的参数,就是文本输入框输入的内容。
在设置控件的时候,需要将记录的数量转换成String类型。因为setText()里不可以放int类型。
最后显示效果是这样的,文本个数实时改变显示。