android使用webview加载网页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
package com.example.webview;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public
class
MainActivity extends Activity
{
private
WebView webview;
@SuppressLint(
"SetJavaScriptEnabled"
)
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webview.getSettings();
//设置WebView属性,能够执行Javascript脚本
webSettings.setJavaScriptEnabled(
true
);
//设置可以访问文件
webSettings.setAllowFileAccess(
true
);
//设置支持缩放
webSettings.setBuiltInZoomControls(
true
);
//加载需要显示的网页
webview.loadUrl(
"<a href="
http:
//www.baidu.com"" target="_blank">http://www.baidu.com"</a>);
//设置Web视图
webview.setWebViewClient(
new
webViewClient ());
}
@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
;
}
@Override
//设置回退
//覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
public
boolean onKeyDown(
int
keyCode, KeyEvent event) {
if
((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
//goBack()表示返回WebView的上一页面
return
true
;
}
finish();
//结束退出程序
return
false
;
}
//Web视图
private
class
webViewClient extends WebViewClient {
public
boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return
true
;
}
}
}
|
xml代码
1
2
3
4
5
6
7
8
9
10
11
12
|
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<LinearLayout xmlns:android=
"<a href="
http:
//schemas.android.com/apk/res/android" " target="_blank">http://schemas.android.com/apk/res/android" </a>
android:orientation=
"vertical"
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
>
<WebView
android:id=
"@+id/webview"
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
/>
</LinearLayout>
|