如何在Android应用程序中将网页加载到webview中?

时间:2015-01-15 09:17:03

标签: android android-layout webview

我正在尝试制作一个简单的Android应用,将网页加载到WebView

package com.example.abhi.molinahealthcare;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Molina_HealthCare extends ActionBarActivity {
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_molina__health_care);
        WebView myWebView = (WebView) findViewById(R.id.webview);

    webview.getSettings().setJavaScriptEnabled(true);
    webview.setWebViewClient(new MyWebViewClient());
    openURL();
}

private void openURL() {
    webview.loadUrl("http://www.google.com");
    webview.requestFocus();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_molina__health_care, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

活动: -

<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

我无法打开它。我在AndroidManifest.xml中声明了INTERNET权限

1 个答案:

答案 0 :(得分:2)

您没有在webview方法中初始化您正在使用的WebView的openURL对象。通过在webview中初始化myWebView而不是onCreate来执行此操作:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_molina__health_care);
        webview = (WebView) findViewById(R.id.webview);
        ...