我做了一个非常简单的 Android 活动:
public class SimpleActivity extends Activity {
private EditText editText1;
private EditText editText2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout verticalLayout = new LinearLayout(this);
verticalLayout.setOrientation(LinearLayout.VERTICAL);
editText1 = new EditText(this) {
@Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
// TODO Auto-generated method stub
super.onTextChanged(text, start, lengthBefore, lengthAfter);
}
};
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println(s.toString());
}
@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
}
});
editText1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
verticalLayout.addView(editText1);
editText2 = new EditText(this);
editText2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
verticalLayout.addView(editText2);
setContentView(verticalLayout);
}
public EditText getEditText1() {
return editText1;
}
public EditText getEditText2() {
return editText2;
}
}
当我在我的 Android 设备上运行此代码时,会在组件初始化时调用重写的 EditText.onTextChanged() 方法和 TextWatcher.onTextChanged() 方法。当我调用方法 editText1.setText("text") 时,它们也被正确调用
当我在 Roboelectric 测试运行器中创建 SimpleActivity 时,它已创建并且 editText1/editText2 不为空,但是在组件初始化和调用 EditText.setText() 时不会调用 EditText.onTextChanged() 和 TextWatcher.onTextChanged() 如何制作 TextWatcher工作?它是我的应用程序的重要部分,如果不处理文本更改事件,就无法对其进行测试。
请帮忙。