Start Activity Intent on Clicking Text Inside Webview

青春壹個敷衍的年華 提交于 2019-11-28 08:50:45

you can this by define scheme in activity intent filter in manifest. for sample create activity (A) and activity (B) and define in manifest like this :

<activity android:name="A" >
    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="activity_a" />
    </intent-filter>
</activity>
<activity android:name="B" >
    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="activity_b" />
    </intent-filter>
</activity>

if in your html have linke like this:

<a href="activity_b://b">Activity B</a>

when you click it , start activity B. Activity A is similar to it.

you can get source code from Source Code

NOTE : if using webview for this method you must override the method shouldOverrideUrlLoading() and compare the every url.

We can use webview same as textview also.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView=(WebView)findViewById(R.id.link2);

        /*TextView t3 = (TextView) findViewById(R.id.link);

        t3.setText(
                Html.fromHtml(
                    "<b>text3:</b>  Text with a " +
                    "<a href=\"activity_a://a\">Activity A</a> : " +
                    "<a href=\"activity_b://b\">Activity B</a> "));
        t3.setMovementMethod(LinkMovementMethod.getInstance());*/

        String data= "<html><head></head>"+
                "<b>text3:</b>  Text with a " +
                "<a href=\"activity_a://a\">Activity A</a> : " +
                "<a href=\"activity_b://b\">Activity B</a></html> ";

        webView.loadData(data, "text/html", "utf-8");

        webView.setWebViewClient(new WebViewClient()
        {
            // Override URL
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                if(url.equalsIgnoreCase("activity_a://a")){
                    Intent intent=new Intent(getApplicationContext(),A.class);
                    startActivity(intent);
                }
                else if(url.equalsIgnoreCase("activity_b://b")){
                    Intent intent=new Intent(getApplicationContext(),B.class);
                    startActivity(intent);
                }
                Log.e("URL","URL "+url);
                return true;
            }
        });

    }

I hope this may help others.Thanks!

I think it's because the anchor tag doesn't have an href attribute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!