如何在Android中使用TextWatcher类?

And*_*per 97 android textwatcher android-edittext

任何人都可以告诉我如何掩盖EditText中的子字符串或如何将EditText子字符串输入更改为密码类型或替换为另一个字符,如123xxxxxxxxx3455

 String contents = et1.getText().toString();
 et1.setText(contents.replace.substring(0, contents.length()-2),"*");
Run Code Online (Sandbox Code Playgroud)

请告诉我如何在Android中使用TextWatcher方法.

Din*_*ati 164

用于TextWatcher......

et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 该TextWatcher怎么办?提供更多细节以便更好地理解. (48认同)
  • 但我不知道如何使用TextWatcher你可以解释一下小例子,感谢你的指导 (2认同)

Yai*_*pro 103

TextWatcher接口有3个回调方法,当文本发生更改时,这些方法按以下顺序调用:

beforeTextChanged(CharSequence s, int start, int count, int after)

将更改应用于文本之前调用.
s参数是应用任何更改之前的文本.
start参数是位置的改变部分在文本的开始.
count参数是长度的改变部分中的s,因为序列start位置.
after参数是新序列的长度,其将取代的部分s从序列startstart+count.
不得更改TextView此方法中的文本(通过使用myTextView.setText(String newText)).

onTextChanged(CharSequence s, int start, int before, int count)

beforeTextChanged方法类似,但文本更改调用.
s参数后的文本已应用的变化.参数与方法中
start参数相同beforeTextChanged.
count参数是afterbeforeTextChanged方法中的参数.
before参数是count在beforeTextChanged方法参数.
不得更改TextView此方法中的文本(通过使用myTextView.setText(String newText)).

afterTextChanged(Editable s)

可以更改TextView此方法中的文本.
/!\警告:当您更改文本时TextView,TextWatcher将再次触发,启动无限循环.然后你应该添加一个boolean _ignore阻止无限循环的属性.
例:

new TextWatcher() {
        boolean _ignore = false; // indicates if the change was made by the TextWatcher itself.

        @Override
        public void afterTextChanged(Editable s) {
            if (_ignore)
                return;

            _ignore = true; // prevent infinite loop
            // Change your text here.
            // myTextView.setText(myNewText);
            _ignore = false; // release, so the TextWatcher start to listen again.
        }

        // Other methods...
    }
Run Code Online (Sandbox Code Playgroud)

摘要:

在此输入图像描述


一个随时可用的课程: TextViewListener

就个人而言,我制作了自定义文本监听器,它为我提供了4个不同字符串的部分,对我来说,使用它更加直观.

 /**
   * Text view listener which splits the update text event in four parts:
   * <ul>
   *     <li>The text placed <b>before</b> the updated part.</li>
   *     <li>The <b>old</b> text in the updated part.</li>
   *     <li>The <b>new</b> text in the updated part.</li>
   *     <li>The text placed <b>after</b> the updated part.</li>
   * </ul>
   * Created by Jeremy B.
   */

  public abstract class TextViewListener implements TextWatcher {
    /**
     * Unchanged sequence which is placed before the updated sequence.
     */
    private String _before;

    /**
     * Updated sequence before the update.
     */
    private String _old;

    /**
     * Updated sequence after the update.
     */
    private String _new;

    /**
     * Unchanged sequence which is placed after the updated sequence.
     */
    private String _after;

    /**
     * Indicates when changes are made from within the listener, should be omitted.
     */
    private boolean _ignore = false;

    @Override
    public void beforeTextChanged(CharSequence sequence, int start, int count, int after) {
        _before = sequence.subSequence(0,start).toString();
        _old = sequence.subSequence(start, start+count).toString();
        _after = sequence.subSequence(start+count, sequence.length()).toString();
    }

    @Override
    public void onTextChanged(CharSequence sequence, int start, int before, int count) {
        _new = sequence.subSequence(start, start+count).toString();
    }

    @Override
    public void afterTextChanged(Editable sequence) {
        if (_ignore)
            return;

        onTextChanged(_before, _old, _new, _after);
    }

    /**
     * Triggered method when the text in the text view has changed.
     * <br/>
     * You can apply changes to the text view from this method
     * with the condition to call {@link #startUpdates()} before any update,
     * and to call {@link #endUpdates()} after them.
     *
     * @param before Unchanged part of the text placed before the updated part.
     * @param old Old updated part of the text.
     * @param aNew New updated part of the text?
     * @param after Unchanged part of the text placed after the updated part.
     */
    protected abstract void onTextChanged(String before, String old, String aNew, String after);

    /**
     * Call this method when you start to update the text view, so it stops listening to it and then prevent an infinite loop.
     * @see #endUpdates()
     */
    protected void startUpdates(){
        _ignore = true;
    }

    /**
     * Call this method when you finished to update the text view in order to restart to listen to it.
     * @see #startUpdates()
     */
    protected void endUpdates(){
        _ignore = false;
    }
  }
Run Code Online (Sandbox Code Playgroud)

例:

myEditText.addTextChangedListener(new TextViewListener() {
        @Override
        protected void onTextChanged(String before, String old, String aNew, String after) {
           // intuitive usation of parametters
           String completeOldText = before + old + after;
           String completeNewText = before + aNew + after;

           // update TextView
            startUpdates(); // to prevent infinite loop.
            myEditText.setText(myNewText);
            endUpdates();
        }
}
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 39

补充答案

这是对其他答案的视觉补充.我对代码和解释的更全面的答案就在这里.

  • 红色:即将删除的文本(已替换)
  • 绿色:刚刚添加的文本(替换旧的红色文本)

在此输入图像描述


Fra*_*cis 7

对于Kotlin使用KTX 扩展功能:( TextWatcher用作以前的答案)

yourEditText.doOnTextChanged { text, start, count, after -> 
        // action which will be invoked when the text is changing
    }
Run Code Online (Sandbox Code Playgroud)


进口core-KTX

implementation "androidx.core:core-ktx:1.2.0"
Run Code Online (Sandbox Code Playgroud)


小智 6

在Android中使用TextWatcher

这是一个示例代码.尝试使用addTextChangedListenerTextView的方法

addTextChangedListener(new TextWatcher() {

        BigDecimal previousValue;
        BigDecimal currentValue;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int
                count) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    currentValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    previousValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (isFirstTimeChange) {
                isFirstTimeChange = false;
                return;
            }
            if (currentValue != null && previousValue != null) {
                if ((currentValue.compareTo(previousValue) > 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_green);
                    setBackgroundColor(flashOnColor);
                } else if ((currentValue.compareTo(previousValue) < 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_red);

                    setBackgroundColor(flashOffColor);
                } else {
                    //setBackgroundColor(textColor);
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000);
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)


Ber*_*sen 5

解决方案的更大视角:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }
Run Code Online (Sandbox Code Playgroud)

这对我有用,这是我第一次这样做。


小智 5

创建自定义TextWatcher子类:

public class CustomWatcher implements TextWatcher {

    private boolean mWasEdited = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (mWasEdited){

            mWasEdited = false;
            return;
        }

        // get entered value (if required)
        String enteredValue  = s.toString();

        String newValue = "new value";

        // don't get trap into infinite loop
        mWasEdited = true;
        // just replace entered value with whatever you want
        s.replace(0, s.length(), newValue);

    }
}
Run Code Online (Sandbox Code Playgroud)

为EditText设置监听器:

mTargetEditText.addTextChangedListener(new CustomWatcher());
Run Code Online (Sandbox Code Playgroud)