如何在AlertDialog中链接部分消息?

时间:2015-03-17 17:04:02

标签: android string onclicklistener alertdialog

是否可以将Dialog消息的一部分作为链接?并为该部分分配一个点击监听器?

我们说我有一个这样的对话:

String message = "Hello, click here for more info";
String messageClickable = "click here";

new AlertDialog.Builder(this)
    .setMessage(message)
    .setPositiveButton("Ok", null)
    .show();

如何使messageClickable部分可点击?我研究了课程Linkify,但我只能找到适用于实际链接或电话号码等的方法addLinks

1 个答案:

答案 0 :(得分:5)

我最终使用的解决方案如下:

private void showDialogWithClickableMessage() {

    String message = "Hello, click here for more info";
    String messageClickable = "click here";

    SpannableString messageSpannable = new SpannableString(message);

    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // do something
        }
    };

    messageSpannable.setSpan(clickableSpan, message.indexOf(messageClickable), message.indexOf(messageClickable) + messageClickable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

    AlertDialog alertDialog = new AlertDialog.Builder(this)
            .setMessage(messageSpannable)
            .setNegativeButton(R.string.alert_action_ok, null)
            .show();

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

}