我是新的蜜蜂到android。为什么如果没有调用setcontentview(),findViewById()返回null?
这里是我的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>
和非常基本的代码 -
@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);
}
输出:
05-10 11:44:15.996: I/System.out(6494): linear layout = [email protected]
05-10 11:44:15.996: I/System.out(6494): linear layout = null
findViewById()
被返回null?为什么?
如果我取消setContentView(view)
并再次运行..
输出:
05-10 11:50:12.781: I/System.out(7791): linear layout = [email protected]
05-10 11:50:12.781: I/System.out(7791): linear layout = [email protected]
什么额外的不setContentView()
是干什么的?
谢谢。那么,这是否意味着如果一个视图与某个活动没有关联,则findViewById()将始终返回null。 – Vipul 2013-05-10 07:38:14
@ user2368689是的,你也可以找到你设置内容的布局视图的id为活动 – Raghunandan 2013-05-10 07:41:09
@Raghunandant,谢谢! – Vipul 2013-05-10 07:53:34