Multiple Clickable links in TextView on Android

后端 未结 8 777
无人共我
无人共我 2020-12-14 07:16

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 Po

8条回答
  •  猫巷女王i
    2020-12-14 08:15

    With Textoo, this can be achieved like:

    res/values/strings.xml:

    
         By signing up you agree to our Terms of Service and Privacy Policy.
    
    

    res/layout/myActivity.xml:

    
    

    java/myPackage/MyActivity.java:

    public class MyActivity extends Activity {
        ...
        protected void onCreate(Bundle savedInstanceState) {
            ...
            TextView termsAndPrivacy = Textoo
                .config((TextView) findViewById(R.id.view_terms_and_privacy))
                .addLinksHandler(new LinksHandler() {
                    @Override
                    public boolean onClick(View view, String url) {
                        if ("terms:".equals(url)) {
                            // Handle terms click
                            return true;  // event handled
                        } else if ("privacy:".equals(url)) {
                            // Handle privacy click
                            return true;  // event handled
                        } else {
                            return false;  // event not handled.  continue default processing i.e. launch web browser and display the link
                        }
                    }
                })
                .apply();
            ...
        }
        ...
    }
    

    This approach have the advantages that:

    • Keep text externalized as string resource. Make it easier to localize your app.
    • Can handle the click event directly using LinksHandler and no need to define additional intent filter
    • Simpler and more readable code

提交回复
热议问题