With the previous versions of AppCompat it was easy to get the ActionBar's title TextView and modify it.
There is the method I was using:
private TextView getActionBarTitleView() {
int id = getResources().getIdentifier("action_bar_title", "id", "android");
return (TextView) findViewById(id);
}
And then to change the alpha's value of the title:
getActionBarTitleView().setAlpha(ratio*255);
Now for some reasons, "action_bar_title" with the lastest AppCompat version isn't working anymore. When I tried to use my method, it returned me "null". Tried to use other id's of the ActionBar but I didn't find the good one.
I saw 1 post on StackOverflow from Ahmed Nawara and the only way he found for the moment was to do an Iteration over the Toolbar's children views and whenever a TexView is found, compare it's text value with the toolbar.getTitle() to make sure that's the TexView we're looking at.
If someone could help me to integrate this solution in my case because I don't know how to do it actually.
I guess you got your method from Flavien Laurent's post on making the ActionBar not boring. If you take a closer look, he detailled another technique to set the ActionBar title's alpha inspired by Cyril Mottier.
It uses a custom AlphaForegroundColorSpan class that extends ForegroundColorSpan :
public class AlphaForegroundColorSpan extends ForegroundColorSpan
{
private float mAlpha;
public AlphaForegroundColorSpan(int color)
{
super(color);
}
public AlphaForegroundColorSpan(Parcel src)
{
super(src);
mAlpha = src.readFloat();
}
public void writeToParcel(Parcel dest, int flags)
{
super.writeToParcel(dest, flags);
dest.writeFloat(mAlpha);
}
#Override
public void updateDrawState(TextPaint ds)
{
ds.setColor(getAlphaColor());
}
public void setAlpha(float alpha)
{
mAlpha = alpha;
}
public float getAlpha()
{
return mAlpha;
}
private int getAlphaColor()
{
int foregroundColor = getForegroundColor();
return Color.argb((int) (mAlpha * 255), Color.red(foregroundColor), Color.green(foregroundColor), Color.blue(foregroundColor));
}
}
Then, using a SpannableString, you just set the alpha to the AlphaForegroundColorSpan, and then set this AlphaForegroundColorSpan to the SpannableString :
public void onCreate(Bundle savedInstanceState)
{
...
spannableString = new SpannableString("ActionBar title");
alphaForegroundColorSpan = new AlphaForegroundColorSpan(0xffffffff);
...
}
private void setActionBarTitle(int newAlpha)
{
alphaForegroundColorSpan.setAlpha(newAlpha);
spannableString.setSpan(alphaForegroundColorSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(spannableString);
}
Hope it helps. If it's not clear enough, give another look to Flavient Laurent's post!
With AppCompat you should use the new toolbar including the toolbar.xml in the activity layout and importing android.support.v7.widget.Toolbar.
In your activity, OnCreate you will have:
mtoolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mtoolbar);
getActionBarTitleView().setAlpha(ratio*255);
at this point you are almost done and you can use reflection to access to the view (remember to import java.lang.reflect.field;) and your function will be:
private TextView getActionBarTitleView() {
TextView yourTextView = null;
try {
Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
yourTextView = (TextView) f.get(mToolBar);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return yourTextView;
}
Related
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!
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!
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);
}
I Want to create mulitple TextView dynamically in ListView item. suppose i use LinearLayout it will create textview horizontal or vertically. I want multiple textview with the wraping. How can i create like that please share your valuable ideas,
Below screen images.
Note :
Each textview have the click action
Mike voted 8 , lara voted 9 like that individual text with wraping conetxt.
I have a custom view (merge xml) that contains a text view (originally it's a more complicated view).
My custom view class like this
public class Example extends LinearLayout {
protected Context context;
protected TextView titleView;
public Example(Context context) {
super(context);
this.context = context;
LayoutInflater inflater = (LayoutInflater) `enter code here`context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.bloghu_title_layout, this, true);
this.setOrientation(LinearLayout.VERTICAL);
titleView = (TextView) getChildAt(0);
}
public void setBlogTitle(String blogTitle, final String blogUrl, String author, final String authorUrl) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append(blogTitle.toUpperCase());
spannableStringBuilder.append(" / ");
spannableStringBuilder.setSpan(new RelativeSizeSpan(1.5f), 0, blogTitle.length() + 2, 0);
spannableStringBuilder.append(author);
spannableStringBuilder.setSpan(new RelativeSizeSpan(1.2f), spannableStringBuilder.length() - author.length(), spannableStringBuilder.length(), 0);
spannableStringBuilder.setSpan(new NonUnderlineClickableSpan() {
#Override
public void onClick(View widget) {
Log.d("span", blogUrl);
}
}, 0, blogTitle.length(), 0);
spannableStringBuilder.setSpan(new NonUnderlineClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(context, authorUrl, Toast.LENGTH_SHORT).show();
}
}, spannableStringBuilder.length() - author.length(), spannableStringBuilder.length(), 0);
spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.index_orange)), 0, blogTitle.length(), 0);
spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.black)),
spannableStringBuilder.length() - author.length(), spannableStringBuilder.length(), 0);
titleView.setMovementMethod(LinkMovementMethod.getInstance());
titleView.setText(spannableStringBuilder, BufferType.SPANNABLE);
}
}
The NonUnderlineClickableSpan() is an extended ClickAbleSpan(), it just because I don't want to underline the clickable text, end it has an empty onclick method that you have to override:
public class NonUnderlineClickableSpan extends ClickableSpan{
#Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false); // set to false to remove underline
}
#Override
public void onClick(View widget) {
// TODO Auto-generated method stub
}
As you can see in Example class you can set a new NonUnderlineClickableSpan, in its' onClick() method you can set what to happen, than you have to set the first and the last character of the clickable span, and a flag (this is the last parameter, in this case 0).
Whit ForegroundSpan you can set font color, whith relative size span you can set different text sizes, and there are a lot of span to style your text and make it interactive, but it is a very under-documented part of android.
I haven't found a good tutorial about this topic yet, so if somebody know one, pls let me know :).
What is the problem, whit textviews in linearLayout? But I think, what you really looking for is spannable string,in this case you can set the formats (colour, font size, style and what ever you want, and onClick actions for every word, and you need just one text view.
In my project I am using the font android: fontFamily = "sans-serif-light", and working properly.
I am also using the library viewpagerindicator. I want to use the font android: fontFamily = "sans-serif-light" also in the viewpagerindicator, but can not find how to do it
I've tried using android:fontFamily = "sans-serif-light" in <com.viewpagerindicator.TitlePageIndicator ... and in style, but without success.
I have also tried:
PageIndicator mIndicator = (TitlePageIndicator) findViewById (R.id.indicator);
Typeface myTypeface = Typeface.createFromAsset (getAssets (), "fonts / Roboto-Light.ttf");
mIndicator.setTypeface (myTypeface);
but this does not work ..
I appreciate any help.
Thanks and regards
If I don't get you wrong, you want to change titles font in view pager indicator,
I changed the library to achieve that,
for TabPageIndicator custome typeface I added this for TabPageIndicator.java
private Typeface mTypeface;
public void setTypeFace(Typeface tf) {
this.mTypeface = tf;
}
and then change addTab function to this:
private void addTab(int index, CharSequence text, int iconResId) {
final TabView tabView = new TabView(getContext());
tabView.mIndex = index;
tabView.setFocusable(true);
tabView.setOnClickListener(mTabClickListener);
tabView.setText(text);
**if (mTypeface != null) {
tabView.setTypeface(mTypeface);
}**
if (iconResId != 0) {
tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
}
mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0, MATCH_PARENT, 1));
}
now you should just setTypeFace on your tabpagerindicator, like this:
mTabPageIndicator = (TabPageIndicator) findViewById(R.id.tab_page_indicator);
mTabPageIndicator.setTypeFace(Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/custome_font.ttf");
I'm using the ViewPageIndicator library, here's how I did it (index is the tab index in your view page indicator):
private void changeTabText(int index, boolean on){
if(tabLayout.getChildCount()-1 >= index){
TextView tv = (TextView)tabLayout.getChildAt(index);
tv.setTextColor(getResources().getColor(on? android.R.color.black : R.color.light_grey));
CustomFont.setTypeface(tv, CustomFont.NORMAL);
}
}
Here's how I got the tablayout:
tabLayout = (ViewGroup)indicator.getChildAt(0); //indicator is a horizontal scroll view, there will be only one root layout
Here's what my custom font does:
public static void setTypeface(TextView view, String font) {
Typeface typeface = Typeface.createFromAsset(view.getContext().getAssets(), BASE_PATH + font);
view.setTypeface(typeface);
}
A more OOD implementation is to modify the Library by creating a new interface:
public interface FontPagerAdapter {
/**
* Get the fonts to set.
*/
Typeface getCustomFont();}
And in class TabPageIndicator.java add a new property:
private Typeface customTypeFace;
which will be set in the notifyDataSetChanged() method by declaring:
if (adapter instanceof FontPagerAdapter) {
FontPagerAdapter fontAdapter = (FontPagerAdapter)adapter;
customTypeFace = fontAdapter.getCustomFont();
}
Later you would change the Font by setting it programatically in the addTab method, just by adding:
if (customTypeFace != null) {
tabView.setTypeface(customTypeFace);
}
Finally in the adapter that will use the library, you need to implement this interface, then override the method:
#Override
public Typeface getCustomFont() {
Typeface font = Typeface.createFromAsset(context.getAssets(),"fonts/PoetsenOne-Regular.ttf");
return font;
}
I have a TextView that displays some HTML code (images included, ImageGetter).
The html is not mine, but I can ask them to include custom scheme links, maybe even tags.
Purpose: to display some dynamically generated content without the need to play with nested Android layouts.
Problem: some links must be handled in the application (new Fragment loaded).
Can't use a receiver for action.VIEW, since it's an Activity Intent, not a broadcast, and its use will be very contextual, so only a programmatically registered receiver would do.
I'm usingtextView.setText(Html.fromHtml(content.content, imageGetter, null). need everything to remain the same, except some spans should have my own onClick on it. I'm not very familiar with Spanned, so I see these options:
Edit the SpannableStringBuilder returned from Html.fromHtml, and replace the URLSpans I want with a custom ClickableSpan (how?)
As above, but copy everything to a new builder, exchanging the URLSpans for my own (how? append takes a CharSequence only, and I get RelativeSizeSpan, StyleSpan, ImageSpan, URLSpan...)
Create a Spanned manually. I can do it for the custom scheme, but how to duplicate the effect of Html.fromHtml (or close enough) for all else?
[edit]
Thanks to MH. for the info. I had tried that before, but failed. Now that i returned to it, I found i had made an error, passing the wrong item to the 1st argument of setSpan.
If anyone's interested, i now use this:
public static interface OnSpanClickListener {
void onClick(String url);
}
public static SpannableStringBuilder getSpannable(String source, ImageGetter imageGetter, String scheme, final OnSpanClickListener clickHandler){
SpannableStringBuilder b = (SpannableStringBuilder) Html.fromHtml(source, imageGetter, null);
for(URLSpan s : b.getSpans(0, b.length(), URLSpan.class)){
String s_url = s.getURL();
if(s_url.startsWith(scheme+"://")){
URLSpan newSpan = new URLSpan(s_url.substring(scheme.length()+3)){
public void onClick(View view) {
clickHandler.onClick(getURL());
}
};
b.setSpan(newSpan, b.getSpanStart(s), b.getSpanEnd(s), b.getSpanFlags(s));
b.removeSpan(s);
}
}
return b;
}
(...)
body.setText(getSpannable(content.content, imageGetter, getResources().getString(R.string.poster_scheme), new OnSpanClickListener(){
public void onClick(String url) {
// do whatever
}
}));
Option 1 is probably most straightforward and most of the hard work for it has already been done before. You've got the general idea correct: after the HTML has been processed, you can request all the generated URLSpan instances and loop through them. You can then replace it with a customized clickable span to get full controls over any of the span clicks.
In the example below, I'm just replacing every URLSpan with a simple extension of that class that takes the original url (actually, I should probably say 'uri') and replace its scheme part. I've left the actual onClick() logic unimplemented, but I'll leave that up to your imagination.
SpannableStringBuilder builder = ...
URLSpan[] spans = builder .getSpans(0, builder .length(), URLSpan.class);
for (URLSpan span : spans) {
int start = builder .getSpanStart(span);
int end = builder .getSpanEnd(span);
s.removeSpan(span);
span = new CustomURLSpan(span.getURL().replace("http://", "scheme://"));
s.setSpan(span, start, end, 0);
}
textView.setText(builder);
As mentioned earlier, here the CustomURLSpan class is a simple extension of URLSpan that takes a url and overrides the onClick() method so our own logic can be executed there.
public class CustomURLSpan extends URLSpan {
public CustomURLSpan(String url) {
super(url);
}
#Override public void onClick(View widget) {
// custom on click behaviour here
}
}
Some related Q&A's that basically do a similar thing (might be helpful for some more inspiration):
Can I change TextView link text after using Linkify?
Remove underline from links in TextView - Android
As you will use TextView.setMovementMethod(LinkMovementMethod.getInstance()) to make it respond for the partly click, you can implement a customized LinkMovementMethod to intercept the click event and process your own logic.
public class CustomLinkMovementMethod extends LinkMovementMethod {
private HashMap<Class, SpanProxy> spansProxy = new HashMap<>();
public CustomLinkMovementMethod setSpanProxy(Class spanClazz, SpanProxy proxy) {
spansProxy.put(spanClazz, proxy);
return this;
}
public CustomLinkMovementMethod removeSpanProxy(Class spanClazz) {
spansProxy.remove(spanClazz);
return this;
}
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
SpanProxy spanProxy = spansProxy.get(ClickableSpan.class);
if(spanProxy != null) {
spanProxy.proxySpan(link[0], widget);
} else {
link[0].onClick(widget);
}
return true;
}
}
}
return super.onTouchEvent(widget, buffer, event);
}
public interface SpanProxy {
void proxySpan(Object span, View widget);
}
}
And used like this:
textView.setMovementMethod(new CustomLinkMovementMethod().setSpanProxy(ClickableSpan.class,
new CustomLinkMovementMethod.SpanProxy() {
#Override
public void proxySpan(Object span, View widget) {
if (span instanceof URLSpan) {
URLSpan urlSpan = (URLSpan) span;
String url = urlSpan.getURL();
// do what you want with the link
// tbd
return;
}
if (span instanceof ClickableSpan) {
((ClickableSpan) span).onClick(widget);
}
}
}));
I am using a TextView for which I have set autolink="web" property in XML file. I have also implemented the onClickListener for this TextView. The problem is, when the text in TextView contains a hyperlink, and if I touch that link, the link opens in browser but simultaneously the onClickListener triggers too. I don't want that.
What I want is, if I touch the hyperlink the clickListener should not fire. It should only fire if I touch the part of the text that is not hyperlinked. Any suggestion?
You can achieve this using a work around in getSelectionStart() and getSelectionEnd() functions of the Textview class,
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClassroomLog.log(TAG, "Textview Click listener ");
if (tv.getSelectionStart() == -1 && tv.getSelectionEnd() == -1) {
//This condition will satisfy only when it is not an autolinked text
//Fired only when you touch the part of the text that is not hyperlinked
}
}
});
It may be a late reply, but may be useful to those who are searching for a solution.
one of the #CommonsWare post helps to intercept autolink OnClick event.
private void fixTextView(TextView tv) {
SpannableString current = (SpannableString) tv.getText();
URLSpan[] spans =
current.getSpans(0, current.length(), URLSpan.class);
for (URLSpan span : spans) {
int start = current.getSpanStart(span);
int end = current.getSpanEnd(span);
current.removeSpan(span);
current.setSpan(new DefensiveURLSpan(span.getURL()), start, end,
0);
}
}
public static class DefensiveURLSpan extends URLSpan {
private String mUrl;
public DefensiveURLSpan(String url) {
super(url);
mUrl = url;
}
#Override
public void onClick(View widget) {
// openInWebView(widget.getContext(), mUrl); // intercept click event and do something.
// super.onClick(widget); // or it will do as it is.
}
}
Apply above code simply as below. It will go through all linkable texts and replace click events to above event handler.
fixTextView(textViewContent);
You can set the property android:linksClickable="false" in your TextView, in conjuction with android:autoLink="web"; this makes the links visible, but not clickable.
if you wish, you can use the next code which allows to customize the clickable links within the string ( based on this post ) :
usage:
final TextView textView = (TextView) findViewById(R.id.textView);
final Spanned text = Html.fromHtml(getString(...));
textView.setText(text);
textView.setMovementMethod(new LinkMovementMethodExt());
LinkMovementMethodExt.java
public class LinkMovementMethodExt extends LinkMovementMethod {
private static LinkMovementMethod sInstance;
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new LinkMovementMethodExt();
return sInstance;
}
#Override
public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {
final int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
final int x = (int) event.getX() - widget.getTotalPaddingLeft() + widget.getScrollX();
final int y = (int) event.getY() - widget.getTotalPaddingTop() + widget.getScrollY();
final Layout layout = widget.getLayout();
final int line = layout.getLineForVertical(y);
final int off = layout.getOffsetForHorizontal(line, x);
final ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
//do something with the clicked item...
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
Kotlin version:
Similar to older answers in Java. Simply:
In Layout Editor/XML, add the types of things you'd like to hyperlink via the autoLink property.
<TextView
...
android:autoLink="web|phone|email" />
Add an onClickListener to your TextView in Kotlin code to handle clicks on the plain text part. Check to make sure the person didn't click on a link by checking selectionStart and selectionEnd.
binding.messageText.setOnClickListener { view ->
if (binding.messageText.selectionStart == -1 && binding.messageText.selectionEnd == -1) {
// do whatever you want when they click on the plain text part
}
}
Use textView.getSelectionStart() and textView.getSelectionEnd().If u click any text other than link textView.getSelectionStart() and textView.getSelectionEnd() will be -1 .So by using a if condition in onClickListner you can block the onClick action when link is clicked .
//inside onClickListner
if(textView.getSelectionStart()==-1&&textView.getSlectionEnd==-1){
//onClick action
}
private void fixTextView(TextView tv) {
SpannableString current = (SpannableString) tv.getText();
URLSpan[] spans =
current.getSpans(0, current.length(), URLSpan.class);
for (URLSpan span : spans) {
int start = current.getSpanStart(span);
int end = current.getSpanEnd(span);
current.removeSpan(span);
current.setSpan(new DefensiveURLSpan(span.getURL()), start, end,
0);
}
}
public static class DefensiveURLSpan extends URLSpan {
public final static Parcelable.Creator<DefensiveURLSpan> CREATOR =
new Parcelable.Creator<DefensiveURLSpan>() {
#Override
public DefensiveURLSpan createFromParcel(Parcel source) {
return new DefensiveURLSpan(source.readString());
}
#Override
public DefensiveURLSpan[] newArray(int size) {
return new DefensiveURLSpan[size];
}
};
private String mUrl;
public DefensiveURLSpan(String url) {
super(url);
mUrl = url;
}
#Override
public void onClick(View widget) {
// openInWebView(widget.getContext(), mUrl); // intercept click event and do something.
// super.onClick(widget); // or it will do as it is.
}
}
You would then call fixTextView(textViewContent); on the view after it is declared (via inflation or findViewById) or added to the window (via addView)
This includes the missing requirement to set a CREATOR when extending a Parcelable.
It was proposed as an edit, but rejected. Unfortunately, now future users will have to find out the original one is incomplete first. Nice one, reviewers!
Instead of using a onClickListener, you can try this.
private void addLink() {
tvLink = (TextView) findViewById(R.id.tvInfo2);
String strURL = UrlLoader.getCodeUrl();
// Make the url string clicable and take action in its onclick
SpannableString spanUrl = SpannableString.valueOf(strURL);
spanUrl.setSpan(new InternalURLSpan(new OnClickListener() {
public void onClick(View v) {
//Do Some action
}
}), 0, spanUrl.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tvLink.setText(spanUrl);
// We probably also want the user to jump to your link by moving the
// focus (e.g. using the trackball), which we can do by setting the
// proper movement method:
MovementMethod m = tvLink.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tvLink.getLinksClickable()) {
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
Also in the layout XML file , dont forget to add
<TextView android:layout_width="wrap_content" android:linksClickable="true"
android:layout_height="wrap_content" android:id="#+id/tvInfo2" android:text="#string/url_link" />
Just adding
textView.setMovementMethod(CustomLinkMovementMethod.getInstance());
to #binary's answer for those whose the method did not work with them