android 中如何限制 EditText 最大输入字符数(2)
16lz
2021-12-04
方法四:
基本思路同方法三,监听 EditText 当中输入字符串的长度,如果超长,给出提示。
package cie.textEdit;import android.app.Activity;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.widget.EditText;import android.widget.Toast;public class TextEditActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);final EditText editText = (EditText)findViewById(R.id.entry);editText.addTextChangedListener(new TextWatcher(){private int selectionStart = 0;private int selectionEnd = 0;private CharSequence temp = null;public void afterTextChanged(Editable arg0) {// TODO Auto-generated method stubselectionStart = editText.getSelectionStart();selectionEnd = editText.getSelectionEnd();Log.i(myConstant.Tag,"selectionStart" + selectionStart);if(temp.length() > myConstant.TextMaxLen){Toast.makeText(TextEditActivity.this, R.string.string_limit, Toast.LENGTH_SHORT).show();arg0.delete(selectionStart-1, selectionEnd);int tempSelection = selectionStart;editText.setText(arg0);editText.setSelection(tempSelection);}}public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {// TODO Auto-generated method stubtemp = arg0;}public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {// TODO Auto-generated method stub}});}}
更多相关文章
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用
- python list.sort()根据多个关键字排序的方法实现
- Android(安卓)系统应用调用,intent 的使用方法总结
- Android各种获取Context方法
- android 8.1 开机壁纸下半部分黑屏2-3秒的问题解决
- 详解Android使用@hide的API的方法
- Android(安卓)自绘输入框
- onRetainNonConfigurationInstance和getLastNonConfigurationIns