在Android的Editext的InputFilter过滤器


/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.text;

/**
 * InputFilters can be attached to {@link Editable}s to constrain the
 * changes that can be made to them.
 */
//InputFilter接口,需要重写filter方法
public interface InputFilter
{
    /**
     * This method is called when the buffer is going to replace the
     * range <code>dstart &hellip; dend</code> of <code>dest</code>
     * with the new text from the range <code>start &hellip; end</code>
     * of <code>source</code>.  Return the CharSequence that you would
     * like to have placed there instead, including an empty string
     * if appropriate, or <code>null</code> to accept the original
     * replacement.  Be careful to not to reject 0-length replacements,
     * as this is what happens when you delete text.  Also beware that
     * you should not attempt to make any changes to <code>dest</code>
     * from this method; you may only examine it for context.
     * 
     * Note: If <var>source</var> is an instance of {@link Spanned} or
     * {@link Spannable}, the span objects in the <var>source</var> should be 
     * copied into the filtered result (i.e. the non-null return value). 
     * {@link TextUtils#copySpansFrom} can be used for convenience.
     */

    /** 
      * @param source 输入的文字 
      * @param start 输入-0,删除-0 
      * @param end 输入-source文字的长度,删除-0 
      * @param dest 原先显示的内容 
      * @param dstart 输入-原光标位置,删除-光标删除结束位置 
      * @param dend 输入-原光标位置,删除-光标删除开始位置 
      * @return 
      */
    //主要重写这个方法
    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.
     */
    //接口内的静态内部类,,,输入小写转换成大写
    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.
     */
    
    // 长度过滤器,限制输入的长度
    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 "";
            } 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;
        }
    }
}
详细使用参考:https://www.jianshu.com/p/b24dddaf64ab

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android EditText中,可以通过调用EditText的`getSelectionStart()`和`getSelectionEnd()`方法来获取光标的位置。这两个方法返回的是光标所在位置的索引值,可以用于判断光标的位置。举个例子,如果要判断光标是否在EditText中的第一个字符位置,可以这样写: ``` int selectionStart = editText.getSelectionStart(); if (selectionStart == 0) { // 光标在第一个字符位置 } else { // 光标不在第一个字符位置 } ``` 在InputFilter中,可以通过传入的`source`参数来获取用户输入的文本,`start`参数表示用户输入的文本的起始位置,`end`参数表示用户输入的文本的结束位置。通过这些参数,可以计算出光标所在的位置。例如,要限制用户输入的文本长度不能超过10个字符,可以这样写: ``` public class MyInputFilter implements InputFilter { private int maxLength = 10; @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int keep = maxLength - (dest.length() - (dend - dstart)); if (keep <= 0) { // 已经达到最大长度,不能再输入 return ""; } else if (keep >= end - start) { // 可以输入全部文本 return null; } else { // 只能输入部分文本 int selectionStart = editText.getSelectionStart(); if (selectionStart < dstart || selectionStart > dend) { // 光标不在待插入的文本范围内,不需要调整光标位置 return source.subSequence(start, start + keep); } else { // 光标在待插入的文本范围内,需要调整光标位置 int newSelectionStart = dstart + keep; editText.setSelection(newSelectionStart); return source.subSequence(start, start + keep); } } } } ``` 这里的`editText`是指要限制长度的EditText对象。在`filter`方法中,首先判断已经输入的文本长度是否已经达到最大长度,如果达到了最大长度,就返回空字符串,表示不能再输入了。如果还可以继续输入,就计算出可以输入的文本长度`keep`,然后判断用户输入的文本长度是否超过`keep`,如果超过了,就只能输入部分文本,同时需要调整光标的位置;如果没有超过,就可以输入全部文本,不需要调整光标的位置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值