findViewById返回null的WebView [英] findViewById returns null for WebView
本文介绍了findViewById返回null的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想建立一个Android应用程序,刚刚由一个网页视图中。我从 Android开发人员网站并修改了它的例子。但是,因为它看起来简单,findViewById每次调用导致空指针。
在java文件:
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);
}
}
布局文件:
<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 ...
推荐答案
更改为
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");
}
}
您需要调用 findViewById
前将布局到活动的内容。 findViewById
查找与充气当前布局提供的ID景色。
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.
这篇关于findViewById返回null的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文