I am trying to show in an android AlertDialog some text and some words to be clickable opening a web page. I am doing something wrong with it cause it does not open the link i am telling him and the hole text is clickable, which i am trying to avoid….
This is my code:
final SpannableString s = new SpannableString(
Html.fromHtml("<br><a href=\"http://google.com\">a new link</a>")
);
final TextView tx1 = new TextView(this);
tx1.setText(getString(R.string.librarytextpart1)
+ s
+ getString(R.string.librarytextpart2));
tx1.setAutoLinkMask(RESULT_OK);
tx1.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(s, Linkify.ALL);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.library))
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
})
.setView(tx1).show();
When clicked on the SpannableString text in dialog, it shows the entire text is clickable … and still does not open a webpage. For sure I don’t understand something right from the documentation, but don’t see what. Can you help, please?
With Html.fromHtml() you receive the already formatted HTML text from a given String.
Applied to your case this would result in a “a new link” – but the “href” below is ignored by the Alert Dialog as it is not displaying HTML. So the linkifier does nothing on your code. Try commenting it out – the behaviour will keep the same.
With the Linkifier, you are able to turn arbitrary patterns of text (RegExes) into clickable Links. You may append for example a String matching your Regular Expression to a predefined “base” content URI. So it does not only work for Websites but for every Content URI used on Android. For more Info on that refer to the Google DevSite.
You could use the Linkifier without Regular Expressions, there are a some standard patterns included. These are matching eMail-adresses, phone numbers, map coordinates or a website. So in order to make your solution work:
And it will work.
I adjusted your code, now in the AlertWindow, the URL “www.google.com” should be clickable: