我有一个自定义对话框,里面有一个Textview。我想添加一个文本的超链接。我尝试使用setMovementMethod(LinkMovementMethod.getInstance())
,但它仍然无法正常工作。但是,当我将它应用于不在我的自定义对话框中的textview时,它可以工作。
这是我的对话。
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());
我的字符串资源:
<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" />
使用此行:
text.setText(Html.fromHtml(context.getResources().getString(R.string.my_link)));
尝试将你的text.setMovementMethod(LinkMovementMethod.getInstance());
移到dialog.show();
之前,
由于您在string.xml中定义了html文本,因此请尝试按如下所示进行操作,然后将其设置为textview。
mTextView.setText(getText(R.string.my_styled_text));
这样就可以获得带有样式的文本,不仅仅是getString()
的字符串,因此你不需要Html.fromHtml()
。
注意: - getString()可能要求您将字符串括在CDDATA中,如: -
<string name="foo"><![CDATA[<a href="https://www.google.com/">Link</a>]]></string>
终于解决了。丢失了2件事。
首先,我必须将我的字符串括在CDATA中,如下所示:
<string name="my_link"><![CDATA[<a href="https://www.google.com/">%1$s</a>]]></string>
然后我改变了这一行:
text.setText(Html.fromHtml(getResources().getString(R.string.my_link, str)));