From 83ca0170d8c29a0697e98ea0d395c5a151f21029 Mon Sep 17 00:00:00 2001 From: Damyan Ivanov Date: Sat, 6 Mar 2021 18:08:31 +0200 Subject: [PATCH] HelpDialog: support for markdown-style links in the message --- .../net/ktnx/mobileledger/ui/HelpDialog.java | 48 +++++++++++++++++-- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/net/ktnx/mobileledger/ui/HelpDialog.java b/app/src/main/java/net/ktnx/mobileledger/ui/HelpDialog.java index 984eeeba..2a2bf036 100644 --- a/app/src/main/java/net/ktnx/mobileledger/ui/HelpDialog.java +++ b/app/src/main/java/net/ktnx/mobileledger/ui/HelpDialog.java @@ -19,21 +19,61 @@ package net.ktnx.mobileledger.ui; import android.app.AlertDialog; import android.content.Context; +import android.text.SpannableStringBuilder; +import android.text.Spanned; import android.text.TextUtils; +import android.text.method.LinkMovementMethod; +import android.text.style.URLSpan; +import android.widget.TextView; import androidx.annotation.ArrayRes; import androidx.annotation.StringRes; import net.ktnx.mobileledger.R; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class HelpDialog { + private final static Pattern MARKDOWN_LINK_PATTERN = + Pattern.compile("\\[([^\\[]+)]\\(([^)]*)\\)"); public static void show(Context context, @StringRes int title, @ArrayRes int content) { AlertDialog.Builder adb = new AlertDialog.Builder(context); adb.setTitle(title); - adb.setMessage(TextUtils.join("\n\n", context.getResources() - .getStringArray(content))); + String message = TextUtils.join("\n\n", context.getResources() + .getStringArray(content)); + + SpannableStringBuilder richTextMessage = new SpannableStringBuilder(); + while (true) { + Matcher m = MARKDOWN_LINK_PATTERN.matcher(message); + if (m.find()) { + richTextMessage.append(message.substring(0, m.start())); + String linkText = m.group(1); + assert linkText != null; + String linkURL = m.group(2); + assert linkURL != null; + + if (linkText.isEmpty()) + linkText = linkURL; + + int spanStart = richTextMessage.length(); + richTextMessage.append(linkText); + richTextMessage.setSpan(new URLSpan(linkURL), spanStart, + spanStart + linkText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + URLSpan linkSpan = new URLSpan(linkText); + + message = message.substring(m.end()); + } + else { + richTextMessage.append(message); + break; + } + } + adb.setMessage(richTextMessage); adb.setPositiveButton(R.string.close_button, (dialog, buttonId) -> dialog.dismiss()); - adb.create() - .show(); + final AlertDialog dialog = adb.create(); + dialog.show(); + ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod( + LinkMovementMethod.getInstance()); } } -- 2.39.5