Created
March 1, 2019 12:51
-
-
Save Bramengton/bff3febb780dc93800c5890b2aca5fac to your computer and use it in GitHub Desktop.
SpannableUrl - A simple way to show/select/click url links from HTML text on TextView #TextView #URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Bramengton on 01.03.19. | |
* HTML text: <string name="text_html"><![CDATA[This is link <a href=http://google.com>Google</a>]]></string> | |
* HOW TO USE: setTextViewHTML((TextView) findViewById(R.id.link), getString(R.string.text_html)); | |
*/ | |
public class SpannableUrl extends SpannableStringBuilder { | |
public OnLinkClickListener mListener; | |
public interface OnLinkClickListener{ | |
void onClick(URLSpan span); | |
} | |
public SpannableUrl(final OnLinkClickListener listener){ | |
super(); | |
this.mListener = listener; | |
} | |
private void makeLinkClickable(final URLSpan span) { | |
int start = getSpanStart(span); | |
int end = getSpanEnd(span); | |
int flags = getSpanFlags(span); | |
ClickableSpan clickable = new ClickableSpan() { | |
public void onClick(@NonNull View view) { | |
if(mListener!=null) mListener.onClick(span); | |
} | |
}; | |
setSpan(clickable, start, end, flags); | |
removeSpan(span); | |
} | |
public void setTextUrlLink(final AppCompatTextView text, String html){ | |
CharSequence sequence = Html.fromHtml(html); | |
this.append(sequence); | |
// SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence); | |
URLSpan[] urls = getSpans(0, sequence.length(), URLSpan.class); | |
for(URLSpan span : urls) { | |
makeLinkClickable(span); | |
} | |
text.setText(this); | |
text.setMovementMethod(LinkMovementMethod.getInstance()); | |
} | |
public void setTextUrlLink(Activity act, int textViewRes, @StringRes int html){ | |
View v = act.findViewById(textViewRes); | |
if(v instanceof AppCompatTextView) setTextUrlLink((AppCompatTextView) v, act.getString(html)); | |
} | |
public void setTextUrlLink(AppCompatTextView v, @StringRes int html){ | |
setTextUrlLink(v, v.getContext().getString(html)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment