当前位置:网站首页>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
边栏推荐
- Vs 2019 configure tensorrt to generate engine
- Agile certification (professional scrum Master) simulation exercise-2
- Notifydatasetchanged not applicable to recyclerview - notifydatasetchanged not working on recyclerview
- Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training
- Pytoch configuration
- 销毁Session和清空指定的属性
- VS 2019安装及配置opencv
- MySql实战45讲【行锁】
- Change cell color in Excel using C - cell color changing in Excel using C
- 基于Qt的yolov5工程
猜你喜欢
Spark on yarn resource optimization ideas notes
Sous - système I2C (IV): débogage I2C
umi 路由拦截(简单粗暴)
MySql实战45讲【全局锁和表锁】
分布式事务
Docker install MySQL
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
MySQL practice 45 [SQL query and update execution process]
MySql实战45讲【行锁】
I2C 子系統(四):I2C debug
随机推荐
Force freeing memory in PHP
Bigvision code
Variable declarations following if statements
敏捷认证(Professional Scrum Master)模拟练习题-2
【PyG】理解MessagePassing过程,GCN demo详解
力扣------网格中的最小路径代价
On the adjacency matrix and adjacency table of graph storage
Anhui University | small target tracking: large-scale data sets and baselines
I2C 子系統(四):I2C debug
C#通用接口调用
@Accessors annotation function specifies that the prefix follows the hump naming
Do you really understand relays?
Change cell color in Excel using C - cell color changing in Excel using C
C# WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
MySql实战45讲【事务隔离】
MySql實戰45講【SQL查詢和更新執行流程】
Opengauss database development and debugging tool guide
销毁Session和清空指定的属性
Limit of one question per day
I2C subsystem (I): I2C spec