1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
TextView textView = root.findViewById(R.id.hoge); String link_text = "こちら"; String link_url = "https://hoge.com"; addHyperLink(textView, link_text, link_url, this);
public static void addHyperLink(TextView textView, String link_text, String link_url, Fragment fragment) { Map<String, String> map = new HashMap<>(); map.put(link_text, link_url); SpannableString ss = MiscUtils.createSpannableString(textView.getText().toString(), map, fragment); textView.setText(ss); textView.setMovementMethod(LinkMovementMethod.getInstance()); }
private static SpannableString createSpannableString(String message, Map<String, String> map, Fragment fragment) {
SpannableString ss = new SpannableString(message);
for (final Map.Entry<String, String> entry : map.entrySet()) { int start = 0; int end = 0;
Pattern pattern = Pattern.compile(entry.getKey()); Matcher matcher = pattern.matcher(message); while (matcher.find()) { start = matcher.start(); end = matcher.end(); break; }
ss.setSpan(new ClickableSpan() { @Override public void onClick(View textView) { String url = entry.getValue(); Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); fragment.startActivity(intent); } }, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE); }
return ss; }
|