这篇文章简单讲解 Android与web的简单交互。
1:Android显示web网页:利用Android的WebView控件展示网页
2:web网页调用Android方法:利用注解的方式将Android的方法公开,在javascript中调用公开的方法。

接下来,展示具体的小例子:

1:WebView显示web网页:

布局:

<WebView  android:id="@+id/loadWeb" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/web" </WebView>

代码:

        webView = (WebView)findViewById(R.id.loadWeb);        //获得对webview的设置        WebSettings settings = webView.getSettings();        //设置允许缩放        settings.setSupportZoom(true);        //设置允许脚本        settings.setJavaScriptEnabled(true);        //设置客户端        webView.setWebChromeClient(new WebChromeClient());        webView.setWebViewClient(new WebViewClient());        //加载网址        webView.loadUrl("http://www.baidu.com");

最后注意配置权限:

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

运行就可以看到百度首页。

2:web调用Android方法:

1:布局:

<WebView  android:id="@+id/loadWeb" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/web" </WebView>

2 : android公开方法:

public class LoadJS {    private Context context;    public LoadJS(Context context){        this.context = context;    }    //以注解的方式公开该方法(webkit是浏览器内核),以供网页调用    @android.webkit.JavascriptInterface    public void MyToast(String cc){        Toast.makeText(context, "我来自网页调用"+cc, Toast.LENGTH_SHORT).show();    }}

3 : 网页调用公开方法:
在Android项目文件夹src–>main下新建assets文件夹,在assets文件夹中新建html页。
html代码,其中的js部分代码可在Android完成注解公开方法后再完成:

<html><head>    <title>网页标题</title>    <script> function clickq(){ <!--获取输入框的值--> var cc = document.getElementById("content").value; <!--调用公开的方法--> android.MyToast(cc); } </script></head><body><input value="点击输入" id="content"/><input type="button" value="按钮" onclick="clickq()" id="button"/></body></html>

运行即可。

更多相关文章

  1. 修改android 睡眠的时间的两种方法
  2. Android 设置颜色的方法总结
  3. Android 中两种方法设置android:gravity 和 android:layout_grav
  4. 在eclipse的android工程里引用android sdk之外的类和方法
  5. android studio 编译的时候出现的错误和解决方法
  6. Android 禁止Edittext弹出系统软键盘 的几种方法
  7. Android Camera 方法分析

随机推荐

  1. Android(安卓)JNI简单实例(android 调用C/
  2. [转]Android(安卓)图形系统剖析
  3. android ellipsize的使用
  4. 使用NetBeans+Android(安卓)SDK+NBAndroi
  5. android:paddingLeft 和 layout_marginLe
  6. android常用组件之TextView组件
  7. Android(安卓)4.2启动代码分析(一)
  8. android:ellipsize省略文字用法
  9. android 相对定位布局方向 RelativeLayou
  10. Android(安卓)studio 启动问题,错误