I’ve made a very simple Android activity:
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;
}
}
When I run this code on my Android device, both overriden EditText.onTextChanged() method & TextWatcher.onTextChanged() methods are called while component is inited. Also they’re correctly called, when I call method editText1.setText(“text”)
When I create SimpleActivity in Roboelectric test runner, it’s created & editText1/editText2 are not null, but EditText.onTextChanged() & TextWatcher.onTextChanged() aren’t called while component init & while calling EditText.setText()
How to make TextWatcher work? It’s importaint part of my application & it can’t be tested without handling text changed events.
Please help.
Using Robolectric 1.1, I tested this code:
I was able to see the TextWatcher.onTextChanged() fire, but not EditText.onTextChanged(). It’d be ideal if both fired, but take a look at https://github.com/pivotal/robolectric/blob/robolectric-1.1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java#L63. It looks like TextWatcher will fire, but onTextChange() doesn’t appear implemented for subclasses.
If you need that functionality, you’ll have to implement it in Robolectric. Unfortunately, Robolectric has gaps in its implementation.