Handle links in TextView by Activity

1. Link creation (don’t forget to change the package name):

        mTextView= (TextView) findViewById(R.id.init_terms_text);
        mTextView.setText(
                Html.fromHtml("By continuing you accept our " +
                        "<a href=\"net.your.packagename://terms\">terms</a> " +
                        " and " +
                        "<a href=\"net.your.packagename://privacy\">privacy policy</a> "));
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
        mTextView.setLinksClickable(true);

2. Add target Activity to AndroidManifest.xml (don’t forget to change the package name):

        <activity android:name=".WebViewActivity">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>

                <action android:name="android.intent.action.VIEW"/>

                <data android:scheme="net.your.packagename"/>
            </intent-filter>
        </activity>

3. Target Activity:

public class WebViewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLog.d("onCreate");
        setContentView(R.layout.activity_web_view);

        String host = getIntent().getData().getHost();

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());

        if (host.equals("terms")) {
            myWebView.loadUrl(" http://terms.com/terms-of-service/");
        } else if (host.equals("privacy")) {
            myWebView.loadUrl("http://privacy.com/privacy-policy/");
        }
    }
}

4. activity_web_view.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView android:id="@+id/webview" 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"/>

5. Internet permission:

<manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.