WebView 链接(或按钮)向 Activity 跳转的几种实现方式

来源:互联网 发布:dns服务器的端口 编辑:程序博客网 时间:2024/05/22 04:52

第一种 ,写一个 JavaScriptinterface 类,里面实现WebView向Activity 页面跳转

public class JavaScriptinterface {Activity mActivity;public JavaScriptinterface(Activity mActivity) {this.mActivity = mActivity;}/** 与js交互时用到的方法,在js里直接调用的 */public void startActivity() {Intent intent = new Intent();intent.putExtra("fromWhich", "webViewUrl");intent.putExtra("replyID", "replyID");intent.setClass(mActivity, Testactvity.class);mActivity.startActivity(intent);}}

而webView 实现 myWebView.addJavascriptInterface(new JavaScriptinterface(this), "android");  添加 这个类,表情为 android,在相应的网页中链接或按钮添加相应JS 

function startActivity() {       android.startActivity();    }
 

JavaScriptinterface  的 startActivity  与 JS中的方法必须一致

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><script type="text/javascript">   function startActivity() {       android.startActivity();    }</script></head><body><a href="#" id="a1" name="a1" onClick="startActivity()">button</a><input type="button" value="Say hello" onClick="startActivity()"/> </body></html>

完整Demo下载: http://download.csdn.net/download/jia635/8766869

方式二:

 通过在 Activity 中 的  <data android:scheme="topicid" />  scheme 去实现,同时这种方式可对外开发,即别的APP中遵循这个 scheme 规则,即可打开注册scheme 的Activity

        <activity
            android:name="com.example.webviewtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />


                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />


                <data android:scheme="topicid" />
            </intent-filter>
        </activity>

      在WebView 的主要代码如下 <a href="topicid://aa.bb:80/test?p=12&d=1" id="a1" name="a1"  >button</a>    超连接和scheme 一直 ,然后通过 Intent 传值可以通过  topicid://aa.bb:80/test?p=12&d=1 字段去截取想要的属性值。 这种方式 不能重写 WebViewClient  方法,不然点击就变为 像这个 topicid://aa.bb:80/test?p=12&d=1 Url 跳转。

方式三:

        通过重写 WebViewClient  ,在 WebViewClient  中 有shouldOverrideUrlLoading(WebView view, String url)  的方法,可以在里面定义 Activity的跳转 ,通过 自定义超链接的Url 格式去进行不同的操作,如:http://www.mofangge.com 为 网页跳转 , blogJump://mofangge.com  链接形式为 向Activity 跳转,通过 url  头部 进行 loadUrl 还是startActivity 的跳转判断。

Demo下载:http://download.csdn.net/detail/jia635/8767179






1 0
原创粉丝点击