0

I have a custom dialog that has a Textview inside. I want to add a hyperlink to the text. I tried using setMovementMethod(LinkMovementMethod.getInstance()) but it is still not working. However it works when I apply it to a textview that is not in my custom dialog.

Here is my dialog.

final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.license_dialog_layout);

    TextView text = dialog.findViewById(R.id.text_dialog);

    String str = "Link";
    text.setText(context.getResources().getString(R.string.my_link, str));

    dialog.show();
    text.setMovementMethod(LinkMovementMethod.getInstance());

My string resource:

<string name="my_link"><a href="https://www.google.com/">%1$s</a></string>

Xml:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:id="@+id/text_dialog" />

Evian Pringle
  • 45
  • 2
  • 9

3 Answers3

0

Use this line :

text.setText(Html.fromHtml(context.getResources().getString(R.string.my_link)));
TREAF ALSHEMERI
  • 409
  • 5
  • 12
0

Try to move your text.setMovementMethod(LinkMovementMethod.getInstance()); to before dialog.show();,

Since you have your html text defined in the string.xml , try geting it as follows and then set it to your textview.

mTextView.setText(getText(R.string.my_styled_text));

This picks up the text with the style , not only string as in case of getString() hence u won't need Html.fromHtml() .

Note :- getString() may require you to enclose the string inside CDDATA like:-

<string name="foo"><![CDATA[<a href="https://www.google.com/">Link</a>]]></string>
Kaveri
  • 1,060
  • 2
  • 12
  • 21
  • Thanks it works. However I should've really updated my answer as my html text in my string.xml is actually a string variable and is not defined in the xml. It is like so: %1$s. So how would I make it work for this kind of text? – Evian Pringle Sep 02 '18 at 11:47
  • refer this page .https://stackoverflow.com/questions/12418279/android-textview-with-clickable-links-how-to-capture-clicks – Kaveri Sep 02 '18 at 12:08
  • If you have string with link as a substring , Clickable span might help you.refer this:-https://stackoverflow.com/questions/10696986/how-to-set-the-part-of-the-text-view-is-clickable – Kaveri Sep 02 '18 at 12:10
0

Finally solved it. 2 things were missing.

First I had to enclose my string in CDATA like so:

<string name="my_link"><![CDATA[<a href="https://www.google.com/">%1$s</a>]]></string>

Then I just changed this line:

text.setText(Html.fromHtml(getResources().getString(R.string.my_link, str)));
Evian Pringle
  • 45
  • 2
  • 9