用Toast来输出一SQL语句,结果当我调用TextView tv = (TextView) findViewById(R.id.toast_tv);时, 总是返回空指针。
找了例子程序, 通过仔细比对, 发现正确的语句应该是TextView tv = (TextView) view.findViewById(R.id.toast_tv); 此处的view是通过一个LayoutInflater对象实例化出来的View, 再次测试发现程序便可以正常运行了。
将Layout文件转换为View,顾名思义,专门供Layout使用的Inflater。虽然Layout也是View的子类,但在android中如果想将xml中的Layout转换为View放入.java代码中操作,只能通过Inflater,而不能通过findViewById(),这一段描述有误,看如下代码 。看下面文档写的已经很清楚。
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- <LinearLayout android:id="@+id/placeslist_linearlayout"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- </LinearLayout>
- </ScrollView>
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.placeslist_linearlayout);
linearLayout.addView(place_type_text);
这是可运行的,这上面的xml中,LinearLayout不再是Layout的代表,而只是一个普通的View。
另外,如果在setContentView(R.layout.main)之前调用findViewById(R.id.x)时也会返回空指针, 应该是由于x对应的对象还未实例化出来的缘故。
参考:http://hi.baidu.com/xuyongjia2006/blog/item/1d94cafef461603c5c6008d7.html