Diberdayakan oleh Blogger.

Senin, 29 Februari 2016

Clickable Link In String for TextView Android

by Joielechong sipayung  |  in pemrograman visual at  Senin, Februari 29, 2016



You can download the working example for this tutorial in Here.

There are some hidden quirk that could be use to make an url link in string working in AppCompatTextView in android.

I found that in custom view (honestly, I just trying it with Material Dialogs), a string with an url only work if we use setMovementMethod for TextView


In Custom View

If we want a string containing an url and html code in custom view like this:
 Created by <b>Joielechong</b> (<a href="http://www.rilixtech.com">rilixtech.com</a>)  
For a TextView in a layout like the following xml file:
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:id="@+id/sample_layout"  
4:    android:layout_width="match_parent"  
5:    android:layout_height="match_parent"  
6:    >  
7:    
8:   <android.support.v7.widget.AppCompatTextView  
9:     android:id="@+id/sample_layout_title"  
10:     android:layout_width="wrap_content"  
11:     android:layout_height="wrap_content"  
12:     android:textSize="18sp"  
13:     />  
14:  </RelativeLayout>  
We can't make it work by using either android:autoLink="all" or android:linksClickable="true". So the following code Won't work:
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:id="@+id/sample_layout"  
4:    android:layout_width="match_parent"  
5:    android:layout_height="match_parent"  
6:    >  
7:    
8:   <android.support.v7.widget.AppCompatTextView  
9:     android:id="@+id/sample_layout_title"  
10:     android:layout_width="wrap_content"  
11:     android:layout_height="wrap_content"  
12:     android:text="@string/test_string_1"  
13:     android:textSize="18sp"  
14:     android:autoLink="all"  
15:     android:linksClickable="true"  
16:     />  
17:    
18:  </RelativeLayout>  
To make it work, we must add a line of code in our working class below:
 textView.setMovementMethod(LinkMovementMethod.getInstance());  
Remember to remove android:autoLink="all" in your layout xml because it render the above code useless.


In Normal View

If we use setMovementMethod for TextView and without android:autoLink="all" attribute in layout, url link will be enabled. Using only android:autolink="all" will also working. By using only android:linksClickable="true" url link will not working at all.

Download the working project Here.


Reference:
How do I make links in a TextView clickable?
I want text view as a clickable link
Android: textview hyperlink
Make a hyperlink textview in android
How to make normal links in TextView clickable?

0 comments:

Silahkan tinggalkan komentar anda: