当前位置:网站首页>Stepping on pits and solutions when using inputfilter to limit EditText
Stepping on pits and solutions when using inputfilter to limit EditText
2022-07-03 03:16:00 【Super hard Golden Toad mushroom】
When we want to do EditText Some restrictions on characters , We usually use InputFilter, By rewriting the inside filter Methods to limit the length of the input , But students who are interested may find , In some specific cases, character substitution coverage may occur —— For example, we use a special input method
//InputFilter Interface , Need to rewrite filter Method
public interface InputFilter
{
/** * @param source Input text * @param start Input -0, Delete -0 * @param end Input -source The length of the text , Delete -0 * @param dest What was originally displayed * @param dstart Input - Original cursor position , Delete - The cursor deletes the end position * @param dend Input - Original cursor position , Delete - The cursor deletes the start position * @return */
// Mainly rewrite this method
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend);
/** * This filter will capitalize all the lower case letters that are added * through edits. */
// Static inner classes within interfaces ,,, Input lowercase to uppercase
public static class AllCaps implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isLowerCase(source.charAt(i))) {
char[] v = new char[end - start];
TextUtils.getChars(source, start, end, v, 0);
String s = new String(v).toUpperCase();
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(s);
TextUtils.copySpansFrom((Spanned) source,
start, end, null, sp, 0);
return sp;
} else {
return s;
}
}
}
return null; // keep original
}
}
/** * This filter will constrain edits not to make the length of the text * greater than the specified length. */
// Length filter , Limit the length of input
public static class LengthFilter implements InputFilter {
private final int mMax;
public LengthFilter(int max) {
mMax = max;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
int keep = mMax - (dest.length() - (dend - dstart));
if (keep <= 0) {
return ""; // The main problem is here , although inputfilter You can limit the length in the input process , But you can't make any changes to the cursor
} else if (keep >= end - start) {
return null; // keep original
} else {
keep += start;
if (Character.isHighSurrogate(source.charAt(keep - 1))) {
--keep;
if (keep == start) {
return "";
}
}
return source.subSequence(start, keep);
}
}
/** * @return the maximum length enforced by this input filter */
public int getMax() {
return mMax;
}
}
}
Encounter this situation related to input method , We can try another method that is more flexible and widely used ——Textwatcher, This method can obtain the cursor position operation during input , More flexible restrictions can be made directly during input . For specific operations, please refer to the class written by a boss below .
package com.example.edittext;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
/** * Customize MyTextWatcher Class implementation TextWatcher Interface , And rewrite the relevant methods * * @author Zouch * */
public class MyTextWatcher implements TextWatcher {
private int limit;// Character limit
private EditText text;// Edit box control
private Context context;// Context object
int cursor = 0;// Used to record the position of the cursor when inputting characters
int before_length;// It is used to mark the length of the content in the edit box before entering a certain content
public MyTextWatcher(EditText text, int limit,
Context context) {
this.limit = limit;
this.text = text;
this.context = context;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
before_length = s.length();
}
/** * s Edit everything in the box 、start The position of the cursor in the edit box ( from 0 Start calculating )、count The number of characters input from the input method of the mobile phone */
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cursor = start;
// Log.e(" At this time, the cursor position is ", cursor + "");
}
@Override
public void afterTextChanged(Editable s) {
// Here you can know the number of words you have entered , You can customize the text control to display the number of characters you have entered in real time according to your needs
Log.e(" At this point, you have entered ", "" + s.length());
int after_length = s.length();// The total length of all contents in the edit box after entering contents
// If the length of characters exceeds the limit , Then remove the part added later , This is the key
if (after_length > limit) {
// How many words more than the maximum limit
int d_value = after_length - limit;
// At this time, the number of words input from the mobile phone
int d_num = after_length - before_length;
int st = cursor + (d_num - d_value);// The starting position of the excess that needs to be deleted
int en = cursor + d_num;// The end position of the excess that needs to be deleted
// call delete() Method to remove the excess content in the edit box
Editable s_new = s.delete(st, en);
// Reset the text of the edit box
text.setText(s_new.toString());
// Set the last displayed position of the cursor to the starting position of the excess part , Optimization experience
text.setSelection(st);
// The pop-up message indicates that the word limit has been exceeded
Toast.makeText(context, " The maximum word limit has been exceeded ", Toast.LENGTH_SHORT).show();
}
}
}
Finally, attach the code links of the two bosses ( The dog's head lives
边栏推荐
- Parameter index out of range (1 > number of parameters, which is 0)
- How do you adjust the scope of activerecord Association in rails 3- How do you scope ActiveRecord associations in Rails 3?
- PAT乙级常用函数用法总结
- I2C 子系统(二):I3C spec
- [algebraic structure] group (definition of group | basic properties of group | proof method of group | commutative group)
- Idea format code idea set shortcut key format code
- umi 路由拦截(简单粗暴)
- VS 2019安装及配置opencv
- Pytorch配置
- 左连接,内连接
猜你喜欢
MySql实战45讲【索引】
敏捷认证(Professional Scrum Master)模拟练习题-2
900W+ 数据,从 17s 到 300ms,如何操作
力扣------网格中的最小路径代价
I2C subsystem (IV): I2C debug
On the adjacency matrix and adjacency table of graph storage
左连接,内连接
I2C 子系统(三):I2C Driver
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)
umi 路由拦截(简单粗暴)
随机推荐
Pat class B common function Usage Summary
Are there any recommended term life insurance products? I want to buy a term life insurance.
labelme标记的文件转换为yolov5格式
VS克隆时显示403错误
MySql实战45讲【行锁】
VS 2019 配置tensorRT生成engine
How to select the minimum and maximum values of columns in the data table- How to select min and max values of a column in a datatable?
将时间戳转为指定格式的时间
About HTTP cache control
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
解决高並發下System.currentTimeMillis卡頓
基于Qt的yolov5工程
Vs 2019 configuration du moteur de génération de tensorrt
3D drawing example
Pytoch configuration
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
45 lectures on MySQL [index]
模糊查詢時報錯Parameter index out of range (1 > number of parameters, which is 0)
MySQL practice 45 lecture [transaction isolation]
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)