findViewById returns null for WebView

谁说胖子不能爱 提交于 2020-01-24 07:23:07

问题


I'm trying to build an android app, which just consists of a webview. I took the example from android dev site and modified it. But as simple as it looks, every call to findViewById results in a null pointer. The .java file:

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WebView webView = (WebView) findViewById(R.id.webview);
        // returns null pointer 
        webView.loadUrl("file:///android_asset/index.html");

        setContentView(webView);
    }
}

The layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

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

</LinearLayout>

And I put following line into the manifest:

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

I'm puzzled ...


回答1:


Change to

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout); // muylayout is your layout.xml
    WebView webView = (WebView) findViewById(R.id.webview);
    // returns null pointer 
    webView.loadUrl("file:///android_asset/index.html");
}
}

You need to set the content of your layout to the activity before calling findViewById. findViewById looks for a view with the id provided in the current layout inflated.




回答2:


Just in case the accepted answer is not working. Since i have two different layouts for phone and tablet but only one have WebView which cause findViewById() get null.



来源:https://stackoverflow.com/questions/18942941/findviewbyid-returns-null-for-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!