在Android中的TextView多个可点击的链接多个、链接、Android、TextView

2023-09-07 17:58:47 作者:Traveler 過客

我试图以类似于一个TextView添加多个环节就是谷歌和放大器; Flipboard的已用自己的条款和条件如下完成和隐私政策下面的屏幕截图所示:

I'm trying to add multiple links in a textview similar to what Google & Flipboard has done below with their Terms and conditions AND Privacy Policy shown in the screen shot below:

到目前为止,我无意中发现使用这种方法

So far I've stumbled on using this approach

textView.setText(Html.fromHtml(MYHTML);  textView.setMovementMethod(LinkMovementMethod.getInstance());

textView.setText(Html.fromHtml(myHtml); textView.setMovementMethod(LinkMovementMethod.getInstance());

在这里MYHTML是A HREF。

where myHtml is a href.

但它并没有给我的控制,我需要如推出一个片段等。

But it doesn't give me control I need e.g to launch a fragment etc.

他们在下面的两个例子是如何做到这一点任何想法?

Any idea how they achieve this in the two examples below?

推荐答案

您可以使用的 Linkify ( android.text.Spannable 的的java.util.regex.Pattern 的 java.lang.String中)

String termsAndConditions = getResources().getString(R.string.terms_and_conditions);
String privacyPolicy = getResources().getString(R.string.privacy_policy);

legalDescription.setText(
    String.format(
        getResources().getString(R.string.message),
        termsAndConditions,
        privacyPolicy)
);
legalDescription.setMovementMethod(LinkMovementMethod.getInstance());

Pattern termsAndConditionsMatcher = Pattern.compile(termsAndConditions);
Linkify.addLinks(legalDescription, termsAndConditionsMatcher, "terms:");

Pattern privacyPolicyMatcher = Pattern.compile(privacyPolicy);
Linkify.addLinks(legalDescription, privacyPolicyMatcher, "privacy:");

然后就可以使用计划加入该计划的启动,例如一个活动的 AndroidManifest 的:

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="terms" />
    <data android:scheme="privacy" />
</intent-filter>

如果你想要做自定义操作,您可以设置意图过滤器,以你目前的活动,这将有singleTop launchmode。

If you want to do a custom action, you can set the intent-filter to your current activity, which will have a singleTop launchmode.

这将导致 onNewIntent 被解雇在那里可以让你的自定义操作:

This will cause onNewIntent to be fired where can make your custom actions:

@Override
protected void onNewIntent(final Intent intent) {
 ...
  if (intent.getScheme().equals(..)) {
    ..
  }
}