首页 > 解决方案 > 如何使 MaterialAlertDialogBu​​ilder 中的 ClickableSpan 链接可点击?

问题描述

我有一个SpannableStringBuilder带有这样ClickableSpan链接的对象,

SpannableStringBuilder ssb = new SpannableStringBuilder("Hi StackOverflow!");

ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(@NonNull View widget) {
        Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
    }
};

ssb.setSpan(clickableSpan, 3, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

当我将其设置为 aTextView并使用后,这工作正常textView.setMovementMethod(LinkMovementMethod.getInstance())

当我将ssb对象设置MaterialAlertDialogBuilder

new MaterialAlertDialogBuilder(this)
                .setTitle("My Dialog")
                .setMessage(ssb)
                .show();

它显示为可单击的链接,但实际上无法单击它 MaterialAlertDialogBu​​ilder 预览 我找不到setMovementMethod用于MaterialAlertDialogBuilder. 有什么办法让它可以点击吗?

标签: androidandroid-alertdialogmaterial-componentsspannablestringbuilderclickablespan

解决方案


这是使您的可扩展内容可点击的代码片段,试一试。

SpannableString s = new SpannableString(msg); // Here msg should have url to enable clicking
Linkify.addLinks(s, Linkify.ALL);

之后将您的警报对话框代码放在这里

//Alert dialog code

然后获取 MaterialAlertDialog 的 textview 的 id,下面的代码行必须在 dialog.show() 之后像这样调用,

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

推荐阅读