WebView 实现MiniBrowser

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;

public class MainActivity extends Activity {

    EditText url;
    Button go;
    WebView web;

    @Override
    protected void 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() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });// 允许内部跳转

        go.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                web.loadUrl(url.getText().toString());
            }
        });

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {//重写回退时间 if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
            web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @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;
    }

}
复制代码

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

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

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

  4.基本的miniBrowser就完成了.


你可能感兴趣的:(WebView 实现MiniBrowser)