Get Editable id in afterTextChanged event

后端 未结 3 1029
孤街浪徒
孤街浪徒 2020-12-11 18:00

I have an Activity that extends TextWatcher to detect changes in certain EditTexts, so it implements:

public void afterTextChanged(Editable s)
相关标签:
3条回答
  • 2020-12-11 18:11

    There's one method to implement this without creating a TextWatcher object for every EditText, but I wouldn't use it:

    protected void onCreate(Bundle savedInstanceState) {
        // initialization...
    
        EditText edit1 = findViewById(R.id.edit1);
        edit1.addTextChangedListener(this);
        EditText edit2 = findViewById(R.id.edit1);
        edit2.addTextChangedListener(this);
    }
    
    private static CharSequence makeInitialString(EditText edit) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.setSpan(edit, 0, 0, Spanned.SPAN_MARK_MARK);
        return builder;
    }
    
    public void afterTextChanged(Editable s) {
        EditText[] edits = s.getSpans( 0, s.length(), EditText.class );
        if (edits.length != 1) {
            // this mustn't happen
        }
    
        // here's changed EditText
        EditText edit = edits[0];
    }
    
    0 讨论(0)
  • 2020-12-11 18:20

    Another option, with fewer anonymous inner classes, would be to simply inspect the currently focused View. If your application for TextWatcher hinges solely on changes made by the user while typing, then the changes will always occur in the View that has current focus. Calling getCurrentFocus() from anywhere inside of an Activity or Window will return the View the user is focused on. From inside a TextWatcher, this will almost assuredly be the specific EditText instance.

    SDK Docs Link

    Hope that Helps!

    0 讨论(0)
  • 2020-12-11 18:27

    see TextWatcher for more than one EditText basically create your own class to handle the listener with a constructor that defines the edittext you are monitoring and pass the edittext you are assigning.

    0 讨论(0)
提交回复
热议问题