在Webview内单击文本开始活动意图

uLY*_*eus 2 android android-intent android-webview android-xml android-activity

我在xml中有一个webview,如下所示:

 <WebView
        android:id="@+id/webView"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
Run Code Online (Sandbox Code Playgroud)

我正在加载这样的webview:

String webView_text = "Lorem ipsum..............**<a><u>Link to fire intent</u></a>**";

 WebView webView= (WebView) findViewById(R.id.webView);
webView.loadData(String.format(htmlText, webView_text), "text/html", "utf-8");
        webView.setWebViewClient(new WebViewClient()
        {
            // Override URL
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                Intent intent = new Intent(getApplicationContext(),OtherActivity.class);
                startActivity(intent);
                return true;
            }
        });
Run Code Online (Sandbox Code Playgroud)

请注意,我正在使用html标签在字符串(webView_text)中创建链接,并且覆盖了该函数以激发意图。在这种情况下不这样做。这里有什么问题?我不确定Android Webview是否支持该标签(我认为应该支持)。我的错在这里。先谢谢您。

Gol*_*lil 5

您可以通过在清单中的活动意图过滤器中定义方案来做到这一点。为样本创建活动(A)和活动(B)并在清单中进行定义,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

如果在您的html中有这样的链接:

<a href="activity_b://b">Activity B</a>
Run Code Online (Sandbox Code Playgroud)

当您单击它时,启动活动B。活动A与它相似。

您可以从源代码获取源代码

注意:如果将webview用于此方法,则必须重写该方法shouldOverrideUrlLoading()并比较每个url。