当前位置:网站首页>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
边栏推荐
- Unity3d RPG implementation (medium)
- [shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
- Spark on yarn资源优化思路笔记
- Docker install MySQL
- Edit and preview in the back pipe to get the value writing method of the form
- 别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
- Bigvision code
- Last update time of all sqlserver tables
- [error record] the parameter 'can't have a value of' null 'because of its type, but the im
- TCP handshake three times and wave four times. Why does TCP need handshake three times and wave four times? TCP connection establishes a failure processing mechanism
猜你喜欢

Idea format code idea set shortcut key format code

Don't use the new Dede collection without the updated Dede plug-in

I2C 子系统(四):I2C debug

Segmentation fault occurs during VFORK execution

Vs 2019 configuration tensorrt

Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training
![[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling](/img/c3/b9a614001f80345a5c1cb3c68ab27c.jpg)
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling

I2C subsystem (II): I3C spec

Thunderbolt Chrome extension caused the data returned by the server JS parsing page data exception

Sous - système I2C (IV): débogage I2C
随机推荐
Use of El tree search method
[Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
监听对象中值变化及访问
I2C subsystem (IV): I2C debug
Vs 2019 configuration du moteur de génération de tensorrt
Segmentation fault occurs during VFORK execution
How to limit the size of the dictionary- How to limit the size of a dictionary?
How do you adjust the scope of activerecord Association in rails 3- How do you scope ActiveRecord associations in Rails 3?
Réglez la hauteur et lancez le système. Currenttimemillis catton
Spark on yarn资源优化思路笔记
Thunderbolt Chrome extension caused the data returned by the server JS parsing page data exception
[mathematical logic] normal form (conjunctive normal form | disjunctive normal form | major item | minor item | maximal item | minor item | principal conjunctive normal form | principal disjunctive no
Vs 2019 installation and configuration opencv
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions
Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
二维数组中的元素求其存储地址
VS 2019 配置tensorRT生成engine
函数栈帧的创建与销毁
Limit of one question per day
MySQL practice 45 [SQL query and update execution process]