当前位置:网站首页>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
边栏推荐
- umi 路由拦截(简单粗暴)
- Pytorch配置
- Find the storage address of the elements in the two-dimensional array
- Last update time of all sqlserver tables
- 900W+ 数据,从 17s 到 300ms,如何操作
- Idea set method call ignore case
- About HTTP cache control
- Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence
- @Accessors注解作用指定前缀遵守驼峰命名
- 敏捷认证(Professional Scrum Master)模拟练习题
猜你喜欢

PAT乙级“1104 天长地久”DFS优化思路

Spark on yarn resource optimization ideas notes

Pytorch轻量级可视化工具wandb(local)
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions](/img/4a/1df03d9f3315debb4c335260ed39f2.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions

Elsevier latex 提交文章 pdftex.def Error: File `thumbnails/cas-email.jpeg‘ not found: using draf

Creation and destruction of function stack frame

Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0

VS 2019 配置tensorRT生成engine

C language beginner level - pointer explanation - paoding jieniu chapter

Vs 2019 configuration du moteur de génération de tensorrt
随机推荐
I2C 子系統(四):I2C debug
3D drawing example
复选框的使用:全选,全不选,选一部分
将时间戳转为指定格式的时间
How to use asp Net MVC identity 2 change password authentication- How To Change Password Validation in ASP. Net MVC Identity 2?
Use of check boxes: select all, deselect all, and select some
Distributed transaction
Force deduction ----- the minimum path cost in the grid
umi 路由拦截(简单粗暴)
How to make backgroundworker return an object
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions
程序员新人上午使用 isXxx 形式定义布尔类型,下午就被劝退?
Limit of one question per day
Use of El tree search method
I2C subsystem (IV): I2C debug
Creation and destruction of function stack frame
Do you really understand relays?
Elsevier latex 提交文章 pdftex.def Error: File `thumbnails/cas-email.jpeg‘ not found: using draf
Variable declarations following if statements
What happens between entering the URL and displaying the page?