findViewById返回空指针的解决方法


用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(),这一段描述有误,看如下代码 。看下面文档写的已经很清楚。

 

Xml代码   收藏代码
  1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical"   
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content">  
  5.       
  6.     <LinearLayout android:id="@+id/placeslist_linearlayout"  
  7.         android:layout_width="fill_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:orientation="vertical">  
  10.           
  11.     </LinearLayout>     
  12. </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

http://wayfarer.iteye.com/blog/586156

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值