WebView 实现MiniBrowser

时间:2021-06-22 15:09:58
package org.hjw.minibrowser;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText; publicclass MainActivity extends Activity { EditText url;
Button go;
WebView web; @Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText) findViewById(R.id.url);
go = (Button) findViewById(R.id.go);
web = (WebView) findViewById(R.id.myWebview); WebSettings webSettings = web.getSettings();// 允许使用JS
webSettings.setJavaScriptEnabled(true); web.setWebViewClient(new WebViewClient() {
publicboolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
returntrue;
}
});// 允许内部跳转
go.setOnClickListener(new View.OnClickListener() { @Override
publicvoid onClick(View v) {
web.loadUrl(url.getText().toString());
}
}); } publicboolean onKeyDown(int keyCode, KeyEvent event) {//重写回退时间if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
returntrue;
}
returnsuper.onKeyDown(keyCode, event);
} @Override
publicboolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu);
returntrue;
} }
WebView 实现MiniBrowser

Ps.1.通过WebSettings对象设置允许使用JS.

2.重写OnKeyDown方法实现按Back键返回上一页.

3.使用setWebViewClient方法,实现内部跳转.

4.基本的miniBrowser就完成了.