监听EditText内容变化及字数限制
2016-07-20 15:06
579 查看
需求:Edittext编辑框有字数限制,需要监听Edittext内容并在右下角显示剩余字数
思路:用TextWatcher监听变化
效果图:
1.布局文件 activity_main.xml:
2.代码:
思路:用TextWatcher监听变化
效果图:
1.布局文件 activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/et_content" android:layout_width="match_parent" android:layout_height="200dp" android:hint="请输入不超过10的内容" android:gravity="top"/> <TextView android:id="@+id/tv_left_num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|right" android:layout_margin="10dp"/> </FrameLayout>
2.代码:
public class MainActivity extends Activity { private static final int MAX_NUM = 10; private EditText etContent; private TextView tvLeftNum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etContent = (EditText)findViewById(R.id.et_content); tvLeftNum = (TextView)findViewById(R.id.tv_left_num); tvLeftNum.setText(String.valueOf(MAX_NUM)); etContent.addTextChangedListener(watcher); } TextWatcher watcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //只要编辑框内容有变化就会调用该方法,s为编辑框变化后的内容 Log.i("onTextChanged", s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { //编辑框内容变化之前会调用该方法,s为编辑框内容变化之前的内容 Log.i("beforeTextChanged", s.toString()); } @Override public void afterTextChanged(Editable s) { //编辑框内容变化之后会调用该方法,s为编辑框内容变化后的内容 Log.i("afterTextChanged", s.toString()); if (s.length() > MAX_NUM) { s.delete(MAX_NUM, s.length()); } int num = MAX_NUM - s.length(); tvLeftNum.setText(String.valueOf(num)); } }; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories