afterTextChanged() callback being called without the text being actually changed

℡╲_俬逩灬. 提交于 2019-12-01 13:47:32

问题


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);
}

Edit As @MiloszTylenda have mentioned in the comments it is better to remove the Textwatcher in the onPause() callback to avoid leaking the Textwatcher.

@Override public void onPause() {
  super.onPause();
  myEditText.removeTextChangedListener(watcher);
}


来源:https://stackoverflow.com/questions/13721063/aftertextchanged-callback-being-called-without-the-text-being-actually-changed

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