I am new to Android development (I’m taking a class), so bear with me.
I have to use a TextWatcher to display edited text from an EditText widget into a TextView widget.
For example, if what was initially typed is edited (like if the user typed “Hoozledoofer” and then highlighted “zledoof” and finally typed “v” in its place), I would have to output the change first in the format:
'zledoof' => 'v'
This is shown on the first line of the TextView. Then, the second line would show the full text now present in the EditText widget:
Hoover
I’m not sure how to do this. I know I need to output the results in the afterTextChanged method. How do I save what was done, and still keep it outputting whatever is typed? Any advice?
Below is a TextWatcher example given in class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEdit = (EditText) findViewById(R.id.editText1);
viewText = (TextView) findViewById(R.id.text);
txtEdit.addTextChangedListener (new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.i("TC", "beforeTC " + s.toString() + " "
+ s.subSequence(start, start + count).toString());
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("TC", "onTC " + s.toString() + " "
+ s.subSequence(start, start + count).toString());
}
public void afterTextChanged(Editable s) {
Log.i("TC", "afterTC " + s.toString());
}
});
}
Here’s what I’ve tried which provides the intended final result, but it does keep on showing every little edit made. This may not be an issue and may work for the professor:
txtEdit.addTextChangedListener (new TextWatcher() {
String changed, newStr, edit;
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
changed = s.subSequence(start, start + count).toString();
//Log.i("TC", "beforeTC " + s.toString() + " "
//+ s.subSequence(start, start + count).toString());
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
newStr = s.toString();
edit = s.subSequence(start, start + count).toString();
//Log.i("TC", "onTC " + s.toString() + " "
//+ s.subSequence(start, start + count).toString());
}
public void afterTextChanged(Editable s) {
viewText.setText(changed + " => " + edit + "\n" + newStr);
//Log.i("TC", "afterTC " + s.toString());
}
});
Since this is homework I won’t give you the answer. (Your teacher did much of the busy work by giving you a good example to start with.) But I’ll give you a hint:
Pay attention to
beforeandafterrelative tocount. This will help you know when the user is adding or subtracting text.The second part is easy and you seem to have the answer already: