使用b/s架构;
xml布局文件;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1" />
</RelativeLayout>在assets目录下创建html文件;
html文件;
<html>
<head>
<script type="text/javascript">
function changeUsername()
{
document.all.username.value="java";
}
</script>
</head>
<body>
<input id="username">
<input type="button" onClick="changeUsername();">
</body>
</html>
java代码;
package com.example.androi;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity extends Activity {
private WebView webview;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
setContentView(R.layout.activity_main);
webview=(WebView)findViewById(R.id.webView1);
//应用里面显示浏览器;
webview.setWebViewClient(new WebViewClient());
//执行javascript;
WebSettings storage=webview.getSettings();
storage.setJavaScriptEnabled(true);
//要求网页能适应不同的屏幕;
//给手机用wap;给电脑用www;开头;
webview.loadUrl("file:///android_asset/text.html");;
bt=(Button)findViewById(R.id.button1);
//点击button执行;
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
webview.loadUrl("javascript:changeUsername");
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
本文介绍了一个简单的 Android 应用示例,该应用使用 WebView 控件加载 assets 目录下的 HTML 文件,并通过 JavaScript 进行动态交互。同时展示了如何设置 WebView 的基本属性及如何使用按钮触发 WebView 中 JavaScript 函数的方法。
304

被折叠的 条评论
为什么被折叠?



