Android: How can I add HTML links inside a ListView?

24,476

Solution 1

This is done using the autoLink attribute of a TextView. Took me some time to dig through the documentation so putting it here with an example in case someone else is looking for it:

Let us assume that you are binding your listview to a custom adapter. In that case, the following piece of code goes into your getView call:

Code:

textcontent.setText(Html.fromHtml(item.get_text()));
textcontent.setAutoLinkMask(Linkify.WEB_URLS);

Just put the link inside the text being passed to the setText call and you're done.

XML:

<TextView
                android:id="@+id/txtview"
                android:autoLink="web"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="put your link here"/>

Hope that helps...

Solution 2

If you have text that is already in HTML format, the best thing to do is the following:

TextView textcontent = (TextView) findViewById(...);
textcontent.setMovementMethod(LinkMovementMethod.getInstance());

String text = "<a href="http://www.stackoverflow.com">stackoverflow.com</a>";
textcontent.setText(Html.fromHtml(text));

This will cause any link tags to be clickable in your text view. Alternately, you could use android:autoLink="web" as suggested by Legend, but this has the side-effect of a) linkifying urls that are not wrapped in anchor tags, and b) potentially missing urls or linkifying things that aren't urls. If you want the smarts of autoLink then you should use it, but if all you want is to linkify the tags that are already there, you're better off using setMovementMethod().

See this bug report for more details: http://code.google.com/p/android/issues/detail?id=2219

Solution 3

Hmm, it seems that adding textcontent.setMovementMethod(LinkMovementMethod.getInstance()); makes it so that the clicks on the textview's text parts are no longer passed through to the listview below.

I found a simple workaround under Issue 3414, Comment 27:

An easy way to work around this problem is to call "setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);" on the listView views as they are added. You'll be able to select rows, click on rows and click on child checkboxes and buttons.

It worked perfectly for me, although some casting was required:

View v;
((ViewGroup)v).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

Solution 4

You need to set a function setOnItemClickListener() and inside it declare something like this:

Uri uri = Uri.parse( "http://www.google.com" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
Share:
24,476
Legend
Author by

Legend

Just a simple guy :)

Updated on November 21, 2020

Comments

  • Legend
    Legend over 3 years

    How would I go about adding clickable links inside a ListView?