3

Is it possible to make part of the Dialog message a link? And assign a click listener to that part?

Let's say I have a dialog like this:

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

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

How can I make the messageClickable part clickable? I researched the class Linkify but I could only find method addLinks that works with actual links or phone numbers etc.

Oleksiy
  • 37,477
  • 22
  • 74
  • 122

1 Answers1

9

The solution I ended up using is below:

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());

}
Oleksiy
  • 37,477
  • 22
  • 74
  • 122