为什么TextWatcher事件即使被删除也会被触发?

时间:2014-07-07 19:39:02

标签: android

我使用以下代码在EditText文本发生更改时保持更新类变量。但由于某些原因,在设置EditText的文本后,afterTextChanged会被EditText中的旧值触发。即使我在设置文本之前删除了TextWatcher,也会发生这种情况。知道发生了什么吗?

private EditText mEditCost;
private String mCost;

private TextWatcher myWatcher = new MyTextWatcher()
{
    @Override
    public void afterTextChanged(Editable editable)
    {
        mCost = mEditCost.getText().toString();
    }
};

@Override
protected View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_costs, container, false);
    mEditCost = (EditText)rootView.findViewById(R.id.edit_cost);
    setCost();
    return rootView;
}

private void setCost()
{
    mEditCost.removeTextChangedListener(myWatcher);
    mEditCost.setText(mCost);
    mEditCost.addTextChangedListener(myWatcher);
}

1 个答案:

答案 0 :(得分:0)

这可能是因为在UI中更改了文本后,观察者会收到通知,这是在您调用addTextChangedListener后UI线程返回时发生的。

尝试在下一个UI线程循环中添加观察器:

Handler handler = new Handler();
handler.post(new Runnable(){

   @Override
   public void run(){
       mEditCost.addTextChangedListener(myWatcher);
   }
});
相关问题