32

我有一个片段,EditText里面有一个,onCreateView()TextWatcherEditText.

每次第二次添加片段时,都会afterTextChanged(Editable s)调用回调,而不会更改文本。

这是一个代码片段:

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

我还将片段设置为保留其状态,并将片段的实例保留在活动中。

4

2 回答 2

65

编辑解决方案:

看起来文本在第二次附加片段时发生了更改,因为片段恢复了视图的先前状态。

我的解决方案是在调用之前添加状态,因为text watcher状态onResume()已恢复。onResume

@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);
}
于 2012-12-05T12:34:27.577 回答
8

It seems that this error comes from the fact that Android SDK will call settext when view is coming alive again to recover the state of the EditText. As you can see from the extract below there is a flag that you can change on the Edittext to bypass this behavior.

    <!-- If false, no state will be saved for this view when it is being
         frozen. The default is true, allowing the view to be saved
         (however it also must have an ID assigned to it for its
         state to be saved).  Setting this to false only disables the
         state for this view, not for its children which may still
         be saved. -->
    <attr name="saveEnabled" format="boolean" />

So by adding android:saveEnabled="false" on your EditText will fix the problem and the setText will not be called when view comes to foreground.

This is what I did and problem was solved.

于 2020-10-15T10:52:48.807 回答