Vip*_*pul 1 null android inflate findviewbyid
我是android的新手.
这是我的xml文件 -
<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"
tools:context=".MainActivity"
android:id="@+id/linearlayout"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:id="@+id/textview" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
和非常基本的代码 -
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view=getLayoutInflater().inflate(R.layout.activity_main,null);
//setContentView(view);
LinearLayout ly = (LinearLayout)findViewById(R.id.linearlayout);
Log.i("System.out ","linear layout = " + view);
Log.i("System.out ","linear layout = " + ly);
}
Run Code Online (Sandbox Code Playgroud)
输出:
05-10 11:44:15.996: I/System.out(6494): linear layout = android.widget.LinearLayout@41e34db8
05-10 11:44:15.996: I/System.out(6494): linear layout = null
Run Code Online (Sandbox Code Playgroud)
findViewById()正在返回null?为什么?
如果我取消注释setContentView(view)并再次运行..
输出:
05-10 11:50:12.781: I/System.out(7791): linear layout = android.widget.LinearLayout@41e0d6c8
05-10 11:50:12.781: I/System.out(7791): linear layout = android.widget.LinearLayout@41e0d6c8
Run Code Online (Sandbox Code Playgroud)
还有什么额外setContentView()的事情呢?
public void setContentView (View view)
Run Code Online (Sandbox Code Playgroud)
将活动内容设置为显式视图.此视图直接放在活动的视图层次结构中.
setContentView(View view)是一个活动类的方法.创建活动时,您需要将内容设置为您的活动.
onCreate(Bundle)是初始化活动的地方.最重要的是,在这里,您通常会使用定义UI的布局资源调用setContentView(view),并使用findViewById(int)检索该UI中需要以编程方式进行交互的窗口小部件.
onCreate()的实现应该定义用户界面并可能实例化一些类范围变量.
在布局文件中添加文本视图,drawable等每个资源都会在R.java文件中有一个条目该条目是自动的
例
对于R.java中的activity_main
public static final class layout {
public static final int activity_main=0x7f030000;
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您需要对布局进行充气,但不要将内容设置为活动.
您需要将内容设置为您的活动,然后使用findViewById(..)查找ID.
如果不是,您将获得NullPointerException.
| 归档时间: |
|
| 查看次数: |
2578 次 |
| 最近记录: |