简体   繁体   中英

Android Java Display website in app

I am trying to have a web page appear in my app. This is what I have done:

In my Manifest I added the following code:

<uses-permission android:name="android.permission.INTERNET" />

In my content_main.xml I added the following code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <WebView android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

In my main Activity.java file added the following code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        String url = "http://bigdaddyapp.com";

        webview = (WebView) findViewById(R.id.myWebView);
        //next line explained below
        webview.setWebViewClient(new MyWebViewClient(this));
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl(url);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

But I get the following errors:

在此处输入图片说明

What am I doing wrong?

You have quite a few issues here.

First, you never declare your webView variable. In this case, the fix is simple. You just need to define its type inline:

WebView webview = (WebView) findViewById(R.id.myWebView);

Second, you gave your WebView the ID "webView" in your layout XML, but you try to refer to it via R.id.myWebView . Switch this to use the same ID and it will work.

For the third error, it sounds like you don't actually have a class called MyWebViewClient . Make sure that you do and that it is public.

You also aren't setting the correct layout. You are calling setContentView(R.layout.activity_main) , but your layout is called "content_main."

The rest of the errors should disappear once you fix these issues.

setContentView(R.layout.activity_main);

应该:

setContentView(R.layout.content_main);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM