afterTextChanged() callback being called without t

2019-02-21 07:49发布

问题:

I have a fragment with an EditText and inside the onCreateView() I add a TextWatcher to the EditText.

Each time the fragment is being added for the second time afterTextChanged(Editable s) callback is being called without the text ever being changed.

Here is a code snippet :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
    myEditText = (EditText) v.findViewById(R.id.edit_text);
    myEditText.addTextChangedListener(textWatcher);
...
}

TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        searchProgressBar.setVisibility(View.INVISIBLE);
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.d(TAG, "after text changed");
    }
}

I also set the fragment to retain its state, and I keep the instance of the fragment in the activity.

回答1:

Edited solution:

As it seems the text was changed from the second time the fragment was attached because the fragment restored the previous state of the views.

My solution was adding the text watcher in the onResume() since the state was restored before the onResume was called.

@Override
public void onResume() {
    super.onResume();
    myEditText.addTextChangedListener(textWatcher);
}