Android editText.addTextChangedListener实现还有多少文字可以输入

来源:互联网 发布:企业电话铃声制作软件 编辑:程序博客网 时间:2024/04/28 16:18

今天无聊,
就看见有个小功能挺好的,如下图,

这里写图片描述

其实功能哈市很简单的,就是检测editText中的文字的多少,然后显示在text view上,大致思路就是这样,
首先,我们先把这个布局画一下,我们在EditText
中限制了最大输入为150,

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.administrator.inputtextdemo.MainActivity">    <EditText        android:id="@+id/editText"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:maxLength="150"        android:hint="请输入"/>    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/editText"        android:layout_alignParentRight="true"        android:text="还可以输入0/150"/></RelativeLayout>

2.然后,我们开始使用,

public class MainActivity extends AppCompatActivity {    private TextView textView;    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        editText = (EditText) findViewById(R.id.editText);        textView = (TextView) findViewById(R.id.textView);        editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {            }             @Override            public void afterTextChanged(Editable s) {                textView.setText("还可以输入" + s.length() + "/150");            }        });    }}

在afterTextChanged方法进行设置,这个方法也就是当输入框内容改变的监听,也就是当输入内容改变之后,会调用的。

效果图如下,

这里写图片描述

demo下载地址:

http://download.csdn.net/download/afanbaby/9788555

本人菜鸟一个,有什么不对的地方希望大家指出评论,大神勿喷,希望大家一起学习进步!

1 0
原创粉丝点击