addTextChangedListener и onTextChanged всегда вызываются при загрузке фрагмента Android
у меня есть EditText в Android Fragment. Я придаю addTextChangedListener ему в onCreateView метод. В addTextChangedListener у меня есть onTextChanged метод. Войдя, я вижу, что каждый раз Fragment загружается, onTextChanged называется. С чего бы это? Я хочу, чтобы он вызывался только тогда, когда пользователь фактически изменяет текст в EditText. Вот мой код:
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.detailfragment, container, false);
    final EditText notes = (EditText)view.findViewById(R.id.stitchnotes);
notes.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start,
                int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start,
                int before, int count) {
            Edited = true;
        }
    });
    return view;
}
нашел этот пост и этот пост и мне интересно, должен ли я переместить свой код в onResume. Однако, как вы можете видеть из приведенного выше кода, мне нужен доступ к LayoutInflater и ViewGroup перешло к onCreateView для доступа к EditText, однако, onResume обычно не имеет доступа к этим элементам. Должен ли я использовать onResume? Как я могу справиться с проблемой с LayoutInflater и ViewGroup?
-----------------Дополнительная Информация----------------------
я использовал ответ Тайлера, чтобы решить проблему использования onResume, но onTextChanged все еще вызывается, когда я впервые открываю Fragment. Может кто-нибудь объяснить, почему?  Вот мой измененный код:
private EditText notes;
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.detailfragment, container, false);
    notes = (EditText)view.findViewById(R.id.stitchnotes);
    return view;
}
@Override
public void onResume() {
    super.onResume();
    notes.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start,
                int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start,
                int before, int count) {
            Edited = true;
            Log.w("onTextChanged","Here");
        }
    });
}
<EditText
        android:id="@+id/stitchnotes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="left"
        android:hint="@string/hint"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:inputType="text"
        android:visibility="invisible"
        android:textSize="30dip" />
в тот момент, когда я открываю Fragment, Edited имеет значение true, и LogCat записывается. Я не хочу этого. Я хочу!--23--> установить значение true только тогда, когда пользователь фактически вводит что-то в EditText. Что я делаю не так?
4 ответов
сделать свой EditText член класса. Или сделайте View член класса и вызов findViewById позже.
public class MyFragment extends Fragment {
    private EditText notes;
    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) {
        View view = inflater.inflate(R.layout.detailfragment, container, false);
        notes = (EditText)view.findViewById(R.id.stitchnotes);
        // your other stuff
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        notes.setText("Now I can access my EditText!");
    }
    ...
У меня такая же проблема, но в адаптере. Вышеуказанное решение отлично работает для прямого дочернего элемента представления, но в адаптере представления списка у меня есть проблема. Наконец, я нашел решение с изменением фокуса.
 editQty.setTag(false);
    editQty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            editQty.setTag(true);
        }
    });
    editQty.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().equals("") && (Boolean) editQty.getTag()) {
               // Do your Logic here
                }
            }
        }
    });
общедоступный класс FeedbackFragment расширяет SherlockFragment {
private EditText mEtFeedback;
CustomTextWatcher obj;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_feedback_layout, container, false);
initUIComponents();
obj=new CustomTextWatcher();
mEtFeedback.addTextChangedListener(obj);
return view;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mEtFeedback.removeTextChangedListener(obj);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
    break;
}
}
class CustomTextWatcher implements TextWatcher {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    }
}
}
Маленький И Простой
в основном в этом случае, когда фрагмент загружает последовательность символов onTextChanged, возвращает"", которая не является пустой строкой, поэтому это даст вам лучшую идею
myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().isEmpty()) {
               //control come here when user enter some string to edit text
            } else {
                  //When fragment loads control comes here but below condition prevents execution because s.toString() give ""
                if (!s.toString().equals("")) {
                }
            }
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    });
