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

当在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提示用户已达到最大字符限制;

抱歉,你似乎只复制了代码的一部分,缺失了重要的内容。但是,我可以给你讲解在Activity加载一个Fragment的基本流程。 在Activity加载一个Fragment的基本流程如下: 1. 定义一个继承自Fragment的类,并实现其生命周期方法和相应的UI逻辑。 2. 在Activity实例化该Fragment,并将其添加到Activity。可以使用FragmentManager来进行添加,如下所示: ``` FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { fragment = new CrimeFragment(); fm.beginTransaction() .add(R.id.fragment_container, fragment) .commit(); } ``` 3. 在Activity的布局文件添加一个FrameLayout控件,用于承载Fragment的UI界面。例如: ``` <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 4. 在Fragment编写UI界面的布局文件和逻辑代码,例如: ``` public class CrimeFragment extends Fragment { private Crime mCrime; private EditText mTitleField; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrime = new Crime(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_crime, container, false); mTitleField = (EditText) v.findViewById(R.id.crime_title); mTitleField.addTextChangedListener(new TextWatcher() { // ... }); return v; } } ``` 以上就是在Activity加载一个Fragment的基本流程。希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值