Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a dialog from a hyperlink on text view - Android

There is a way to put a link in some words on a textView and when i click on this word, a dialog is open.

Ex.: TextView --> Word A - Word B - Word C

When i click on Word A, show a Dialog with some options, and when i click on Word C open another dialog with another options.

i checked this link but my problem dont fits.

Open a popup/alert before opening a link in the browser when clicked on a textview

Anyone can help?

like image 212
Rafael Godinho Brandão Avatar asked Nov 02 '25 07:11

Rafael Godinho Brandão


1 Answers

Suppose you are given a “this is a test” String and you wish to show dialog A for the substring “this” and dialog B for the substring “test”. Consider the following method:

private static void applySpan(SpannableString spannable, String target, ClickableSpan span) {
  final String spannableString = spannable.toString();
  final int start = spannableString.indexOf(target);
  final int end = start + target.length();
  spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

The method takes a spannable, searches for the first target occurrence in it and applies the span to it. To show the spannable in a TextView, say from an Activity, you could do the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final SpannableString spannable = SpannableString.valueOf(“this is a test”);
    applySpan(spannable, "this", new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // show dialog A
        }
    });
    applySpan(spannable, "test", new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // show dialog B
        }
    });

    final TextView textView = new TextView(this);
    textView.setText(spannableString);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    setContentView(textView);
}

This is just a crude example, but it hopefully demonstrates a way to solve your problem.

like image 56
Tadej Avatar answered Nov 03 '25 22:11

Tadej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!