I have a string in android :
String meow = "this_is_part1_and_here_another_and_another_one";
I made each word clickable using Clickable
span.
Following is the code for implementing clickable span for each word (adapted from one of Stack Overflow answers)
String meow = "this_is_part1_and_here_another_and_another_one";
String[] tokens = meow.split("_");
ArrayList<String> tokenList = new ArrayList<String>(Arrays.asList(tokens));
if (meow != null || meow.length() != 0 ) {
_field.setMovementMethod(LinkMovementMethod.getInstance());
_field.setText(addClickablePart(meow, tokenList), EditText.BufferType.SPANNABLE);
// _field.addTextChangedListener(new TextWatcher() {
//
// @Override
// public void afterTextChanged(Editable s) {
// Editable ab = new SpannableStringBuilder(s.toString().replace("A", "a"));
// _field.setText(ab);
// Toast.makeText(getApplicationContext(), s.toString(),Toast.LENGTH_LONG).show();
//
// }
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
// });
}
private SpannableStringBuilder addClickablePart(String str, ArrayList<String> clickableWords) {
SpannableStringBuilder ssb = new SpannableStringBuilder(str);
for (String clickableWord : clickableWords) {
int idx1 = str.indexOf(clickableWord);
int idx2 = 0;
while (idx1 != -1) {
idx2 = idx1 + clickableWord.length();
final String clickString = str.substring(idx1, idx2);
ssb.setSpan(new MyClickableSpan(clickString), idx1, idx2, 0);
idx1 = str.indexOf(clickableWord, idx2);
}
}
return ssb;
}
class MyClickableSpan extends ClickableSpan {
String clicked;
public MyClickableSpan(String string) {
super();
clicked = string;
}
public void onClick(View widget) {
Toast.makeText(widget.getContext(), clicked, Toast.LENGTH_LONG).show();
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
}
When I tap a particular word, I show a toast of that word. Now, what I want is when I tap that particular word, after showing that word for few seconds, that word will become blank in EditText, and I type a new word in its place, and get that particular string.
E.g The following is shown in EditText
:
this_is_part1_and_here_another_and_another_one
I tap on word part1
. After showing part1
in toast for few seconds, the word becomes blank in EditText like this:
this_is_ _and_here_another_and_another_one
Now I type a new word in its place say woof
this_is_woof_and_here_another_and_another_one
And I get to store word woof
in a string.
How to do that? In short, how do I make my clickable words associate with TextWatcher? I commented the TextWatcher part as I don't know how to associate it with ClickableSpan. Please help me in this. Thanks.