Reputation: 7856
I have set specific words in a string clickable, and although the functionality is working, the text always highlights a blue color until you press outside of the clickable text onto non-clickable text. Also note that inflating views or pressing any other buttons will keep the text highlighted too. It seems that you have to click on the non-clickable text area to get rid of the highlighted clickable text. How can I prevent the text from highlighting after I click on my clickable selected words? Here is my setup
SpannableString ss = new SpannableString(Html.fromHtml(getActivity().getApplicationContext().getResources().getString(R.string.my_string)));
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Logger.i(TAG, "clicked on clickable words");
}
};
// makes the words clickable
ss.setSpan(clickableSpan, 10, 23, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// makes the clickable words remain red link instead of blue
ss.setSpan(new ForegroundColorSpan(getActivity().getApplicationContext().getResources().getColor(R.color.red)), 30, 43, 0);
tv.setText(ss);
tv.setMovementMethod(LinkMovementMethod.getInstance());
Anyone have any ideas for this? Thanks in advance!
Upvotes: 0
Views: 2048
Reputation: 7856
I found the answer, tv.setHighlightColor(Color.TRANSPARENT)
works. And is the easiest solution compared to overriding ClickableSpan and trying to do something like
import android.graphics.Color;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
public class WordSpan extends ClickableSpan
{
private int id;
private TextPaint textpaint;
public boolean shouldHilightWord = false;
public WordSpan(int anID, String txt, int selected) {
id =anID;
// if the word selected is the same as the ID set the highlight flag
if(selected == id) {
shouldHilightWord = true;
}
}
@Override
public void updateDrawState(TextPaint ds) {
textpaint = ds;
ds.setColor(ds.linkColor);
if(shouldHilightWord){
textpaint.bgColor = Color.GRAY;
textpaint.setARGB(255, 255, 255, 255);
}
//Remove default underline associated with spans
ds.setUnderlineText(false);
}
public void changeSpanBgColor(View widget){
shouldHilightWord = true;
updateDrawState(textpaint);
widget.invalidate();
}
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
}
/**
* This function sets the span to record the word number, as the span ID
* @param spanID
*/
public void setSpanTextID(int spanID){
id = spanID;
}
/**
* Return the wordId of this span
* @return id
*/
public int getSpanTextID(){
return id;
}
}
Hopefully this answer will save someone a lot of work!
Upvotes: 3
Reputation: 14520
Try the below code to remove all color spans from Spannable string :
ForegroundColorSpan[] colorSpans = ss.getSpans(0, ss.length(), ForegroundColorSpan.class);
for(ForegroundColorSpan colorSpan : colorSpans){
ss.removeSpan(colorSpan);
}
Upvotes: 0