鴻飛

导航

 

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.

shareimprove this question
 
    
Each time the fragment is being added for the second time - can you share some code related to this? – Luksprog Dec 5 '12 at 12:18
    
It is a very common thing to do when switching fragments. transaction.replace(r.id.container, fragment); transaction.commit(); nothing special, I have solved the problem with adding a flag I will be posting a solution. – meh Dec 5 '12 at 12:24

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 restoredbefore the onResume was called.

@Override
public void onResume() {
    super.onResume();
    myEditText.addTextChangedListener(textWatcher);
}
shareimprove this answer
 
    
This solution worked for me very well! – GFPF Mar 13 '15 at 18:39
    
Great, that fixed it for me! – Bart Bergmans Jul 23 '15 at 6:51
    
Thank you. This was driving me absolutely crazy. – cohenadair Jan 24 at 5:49
posted on 2016-08-05 19:18  鴻飛  阅读(256)  评论(0编辑  收藏  举报