Android TextView Hyperlink

前端 未结 8 758
悲&欢浪女
悲&欢浪女 2021-02-05 03:45

I\'m implementing a TextView with a string containing two hyperlinks as below but the links are not opening a new browser window:



        
8条回答
  •  抹茶落季
    2021-02-05 03:55

    Here is the solution that worked for me, after looking through multiple Stack Overflow posts. I've tailored it to your implementation:

    1. Remove autolink in favor of using LinkMovementMethod, and set linksClickable to true

    
    

    If you use the android:autoLink="web" property then you'll have to override it with textView.setAutoLinkMask(0); before calling setText() on your TextView. You can also set the link to be clickable in your activity instead like in Harshal's answer if you prefer, but I left it since you already had it in the layout. I also added an id to your TextView called termsOfUse which we'll use later.

    2. Replace < with < in strings.xml and remove double quotes around the url

    This is because when you retrieve the string resource, it won't parse the embedded html correctly, and for some reason it doesn't escape the double quotes. So instead of:

    By continuing, you agree to our Terms of Use and read the Privacy Policy
    

    you'll want to do:

    By continuing, you agree to our <a href=http://link1/terms>Terms of Use</a> and read the <a href=http://link1/privacy>Privacy Policy</a>
    

    3. Parsing the string resource and binding it to our TextView

    Spanned policy = Html.fromHtml(getString(R.string.agree_terms_privacy));
    TextView termsOfUse = (TextView)findViewById(R.id.termsOfUse);
    termsOfUse.setText(policy);
    termsOfUse.setMovementMethod(LinkMovementMethod.getInstance());
    

    Note: Html.fromHtml has been deprecated in API 24 (see this post for more information on how to handle this if needed). We use this method to get the expected HTML formatting from our string.

提交回复
热议问题