首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从字符串资源中获取AlertDialog中可点击的超链接?

如何从字符串资源中获取AlertDialog中可点击的超链接?
EN

Stack Overflow用户
提问于 2010-01-04 11:09:33
回答 15查看 85.4K关注 0票数 138

我想要实现的是在AlertDialog显示的消息文本中有可点击的超链接。尽管AlertDialog实现愉快地对提供的任何超链接(使用传递给Builder.setMessage的字符串资源中的<a href="...">定义)加下划线和颜色,但这些链接不会变为可单击的。

我目前使用的代码如下所示:

代码语言:javascript
复制
new AlertDialog.Builder(MainActivity.this).setTitle(
        R.string.Title_About).setMessage(
        getResources().getText(R.string.about))
        .setPositiveButton(android.R.string.ok, null)
        .setIcon(R.drawable.icon).show();

我希望避免使用WebView来仅显示文本片段。

EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2010-01-05 01:05:36

如果您只在对话框中显示一些文本和URL,那么解决方案可能会更简单

代码语言:javascript
复制
public static class MyOtherAlertDialog {

 public static AlertDialog create(Context context) {
  final TextView message = new TextView(context);
  // i.e.: R.string.dialog_message =>
            // "Test this dialog following the link to dtmilano.blogspot.com"
  final SpannableString s = 
               new SpannableString(context.getText(R.string.dialog_message));
  Linkify.addLinks(s, Linkify.WEB_URLS);
  message.setText(s);
  message.setMovementMethod(LinkMovementMethod.getInstance());

  return new AlertDialog.Builder(context)
   .setTitle(R.string.dialog_title)
   .setCancelable(true)
   .setIcon(android.R.drawable.ic_dialog_info)
   .setPositiveButton(R.string.dialog_action_dismiss, null)
   .setView(message)
   .create();
 }
}

如下所示,http://picasaweb.google.com/lh/photo/up29wTQeK_zuz-LLvre9wQ?feat=directlink

票数 132
EN

Stack Overflow用户

发布于 2010-07-30 06:13:44

我真的不喜欢当前最流行的答案,因为它显着改变了对话框中消息的格式。

这里有一个解决方案,可以在不改变文本样式的情况下链接对话框文本:

代码语言:javascript
复制
    // Linkify the message
    final SpannableString s = new SpannableString(msg); // msg should have url to enable clicking
    Linkify.addLinks(s, Linkify.ALL);

    final AlertDialog d = new AlertDialog.Builder(activity)
        .setPositiveButton(android.R.string.ok, null)
        .setIcon(R.drawable.icon)
        .setMessage( s )
        .create();

    d.show();

    // Make the textview clickable. Must be called after show()
    ((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
票数 211
EN

Stack Overflow用户

发布于 2011-03-28 19:20:39

这应该会让<a href>标签也变得高亮。请注意,我刚刚在emmby的代码中添加了几行代码。所以功劳归功于他

代码语言:javascript
复制
final AlertDialog d = new AlertDialog.Builder(this)
 .setPositiveButton(android.R.string.ok, null)
 .setIcon(R.drawable.icon)
 .setMessage(Html.fromHtml("<a href=\"http://www.google.com\">Check this link out</a>"))
 .create();
d.show();
// Make the textview clickable. Must be called after show()   
    ((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
票数 54
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1997328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档