TextWatcher在模拟器/手机中的行为有所不同

时间:2011-05-24 12:31:14

标签: android textwatcher

我在EditText上有这样的TextWatcher

// the text changed listener for the search field
private TextWatcher searchWatcher = new TextWatcher()
{

  @Override
  public void afterTextChanged(Editable span)
  {
    Log.v(TAG, "afterTextChanged: "+etSearch.getText().toString());
  }

  @Override
  public void beforeTextChanged(CharSequence s, 
                              int start, 
                              int count,
                              int after)
  {
    Log.v(TAG, "beforeTextChanged: "+etSearch.getText().toString()
      +"; start="+start+"; count="+count+"; after="+after);
  }

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count)
  {
    Log.v(TAG, "onTextChanged: "+etSearch.getText().toString());
  }
}

(其中etSearch是我的带有etSearch.addTextChangedListener(searchWatcher)的Edittext。)

我有索尼爱立信Xperia运行2.1-update1和AVD也运行2.1-update1。在模拟器中,我单击EditText,使用软键盘键入abc,然后单击del按钮一次。在手机上,我触摸EditText,在软键盘上键入abc并点击del一次。在电话中,我明白了:

beforeTextChanged: ; start=0; count=0; after=1
onTextChanged: a
afterTextChanged: a

beforeTextChanged: a; start=0; count=1; after=2
onTextChanged: ab
afterTextChanged: ab

beforeTextChanged: ab; start=0; count=2; after=3
onTextChanged: abc
afterTextChanged: abc

beforeTextChanged: abc; start=0; count=3; after=2
onTextChanged: ab
afterTextChanged: ab

在模拟器上,我得到了这个:

beforeTextChanged: ; start=0; count=0; after=1
onTextChanged: a
afterTextChanged: a

beforeTextChanged: a; start=1; count=0; after=1
onTextChanged: ab
afterTextChanged: ab

beforeTextChanged: ab; start=2; count=0; after=1
onTextChanged: abc
afterTextChanged: abc

beforeTextChanged: abc; start=2; count=1; after=0
onTextChanged: ab
afterTextChanged: ab

他们为什么不一样?哪一个是正确的行为?

1 个答案:

答案 0 :(得分:2)

你确定你在两种情况下都做了完全相同的操作吗?虽然不同,但两个结果都有意义。但是,模拟器结果看起来更合乎逻辑。例如:

beforeTextChanged: ab; start=2; count=0; after=1 

对我说,在位置2(开始= 2)你没有更多的字符(count = 0),但你又增加了1个字符(在= 1之后)。这正是您将字符串从ab扩展为abc时发生的情况。

另一方面,Xperia说

beforeTextChanged: ab; start=0; count=2; after=3 

对我说,从位置0开始,你用3个新替换了2个现有字符。在这种情况下,您是否可以删除ab并从开头添加abc

<强>更新

根据更改方式的更新说明,正确的行为是在模拟器上观察到的。

在Nexus One上也观察到与在仿真器上观察到的相同的行为。所以我会说Xperia上的行为更像是异常。