Android中编辑文本时使用TextWatcher和InputFilter.Length

本文介绍如何在Android应用中使用InputFilter和TextWatcher限制EditText的最大输入字符数,并演示了如何设置字符长度限制及将所有输入字母转为大写的示例。

当在EditText或AutoCompleteTextView中编辑内容时,给它限制最大字符,有时在xml文件中设置maxLength属性是失效的,因此可以用InputFilter实现,而监听编辑文本时,用TextWatcher;

1.InputFilter:InputFilters can be attached toEditables to constrain the changes that can be made to them. 

InputFilter.Length:This filter will constrain edits not to make the length of the text greater than the specified length.对编辑的内容设置指定的字符数,从而限制其字符长度;

InputFilter.AllCaps:This filter will capitalize all the lower case letters that are added through edits.即将输入的小写字母转换成大写字母;

2.TextWatcher:When an object of a type is attached to an Editable, its methods will be called when the text is changed.

实现TextWatcher重写三个方法:

afterTextChanged(Editable s):This method is called to notify you that, somewhere within s, the text has been changed.                          

beforeTextChanged(CharSequence s, int start, int count, int after):This method is called to notify you that, withins, the count characters beginning at start are about to be replaced by new text with lengthafter.                          

 

onTextChanged(CharSequence s, int start, int before, int count):This method is called to notify you that, withins, the count characters beginning at start have just replaced old text that had lengthbefore.                          

例:EditText中输入内容时,限制字符数为10;

xml布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_text"
        android:inputType="textMultiLine|textCapWords"/>
</RelativeLayout>

在values文件夹中新建integers.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="edit_max_length">10</integer>
</resources>

java代码:

public class MainActivity extends Activity {

	private EditText editText;
	private int maxLength;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		editText = (EditText) findViewById(R.id.editText);
		// 获取需要指定的字符长度
		maxLength = getResources().getInteger(R.integer.edit_max_length);
		// 设置TextWatcher监听
		editText.addTextChangedListener(new MyEditTextMaxLength(maxLength, this));
		// 使用InputFilter进行过滤,设置最大字符数、英文字母全部大写
		editText.setFilters(new InputFilter[] {
				new InputFilter.LengthFilter(maxLength),
				new InputFilter.AllCaps() });
		/**
		 * 注意;若这里再setFilter();则会覆盖上面的。
		 */
		// editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
	}

	class MyEditTextMaxLength implements TextWatcher {

		private int maxLength;
		private Context context;

		public MyEditTextMaxLength(int maxLength, Context context) {
			this.context = context;
			this.maxLength = maxLength;
		}

		/**
		 * 编辑内容未改变之前回调
		 */
		@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) {

			if (s.toString().length() >= maxLength) {
				Toast.makeText(context, R.string.toast_content,
						Toast.LENGTH_SHORT).show();
			}
		}

	}

}

运行效果:达到maxLength之后就不在输入内容,并且Toast提示用户已达到最大字符限制;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值