Detect if content of EditText was changed by user or programmatically?

丶灬走出姿态 提交于 2019-12-02 16:58:50

This sorted itself out a long time ago, but for anyone who finds their way here looking for an answer, here's what I did:

I ended up setting the Tag of the EditText to some arbitrary value right before I'm about to change it programmatically, and changing the value, and then resetting the Tag to null. Then in my TextWatcher.afterTextChanged() method I check if the Tag is null or not to determine if it was the user or the program that changed the value. Works like a charm!

Something like this:

edit.setTag( "arbitrary value" );
edit.setText( "My Text Value" );
edit.setTag(null);

and then

public void afterTextChanged(Editable s) {
    if( view.getTag() == null )             
        // Value changed by user
    else
        // Value changed by program
}

The accepted answer is perfectly valid, but I have another approach;

@Override
public void onTextChanged(CharSequence charSequence, 
                         int start, int before, int count) {
    boolean userChange = Math.abs(count - before) == 1; 
    if (userChange) { 

    }
}

It works by checking if the change was a single character. This is not a fool-proof solution as copy-paste operations might be missed, and non-user changes of a single character will also be missed. Depending on your use case, this might be a viable solution.

One thing that helped to me is having boolean canListenInput field. Use it inside of watcher.

    email.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (canListenInput) {
                emailChanged = true;
            }
        }
    });

Clear it before changing text programmatically. Set it inside of onAttachedToWindow, (after state) restoration:

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    canListenInput = true;
}

You can do this by adding:

private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
   [your_edittext].removeTextChangedListener(this);

   //Format your string here...

   current = formatted;
   [your_edittext].setText(formatted);
   [your_edittext].setSelection(formatted.length());

   [your_edittext].addTextChangedListener(this);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!