对话框中的Android链接

时间:2012-04-10 19:42:43

标签: android

如何添加对话框消息的链接?

我尝试了以下代码,但链接在onclick上没有做任何事情:

builder.setMessage(Html.fromHtml(
      "Click on the  " +
      "<a href=\"http:\\www.google.com\">link</a> " +
       "to download."));

它也不适用于//www.google.com

3 个答案:

答案 0 :(得分:21)

使用以下代码转换HTML标记(包括可点击的超链接):

((TextView) new AlertDialog.Builder(this)
    .setTitle("Info")
    .setIcon(android.R.drawable.ic_dialog_info)
    .setMessage(Html.fromHtml("<p>Sample text, <a href=\"http://google.nl\">hyperlink</a>.</p>"))
    .show()
    // Need to be called after show(), in order to generate hyperlinks
    .findViewById(android.R.id.message))
    .setMovementMethod(LinkMovementMethod.getInstance());

答案 1 :(得分:0)

对话框的标准实现不允许你做这些花哨的东西。您需要通过为其设置自定义布局内容来创建自定义对话框。例如:

Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.layout_dialog);

有关详情,请参阅thisthis

答案 2 :(得分:0)

您需要使用Linkify

final SpannableString m = new SpannableString(message);
Linkify.addLinks(m, Linkify.WEB_URLS);

    aDialog = new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(m)
            .setNeutralButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        doNeutralClick();
                    }
                }
            )
            .create();

    aDialog.show();

    ((TextView) aDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

请参阅this question