源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android中findViewById返回为空null的快速解决办法

  • 时间:2022-06-26 20:46 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android中findViewById返回为空null的快速解决办法
[b]【问题描述】[/b] Android中如下代码:
LinearLayout groupPollingAddress = (LinearLayout)findViewById(R.layout.fragment_field_list);
返回为null。 [b]【解决过程】[/b] [b]1.参考:[/b] [url=http://stackoverflow.com/questions/20522554/getactivity-findviewbyidr-layout-contacts-list-view-returns-null]android – getActivity().findViewById(R.layout.contacts_list_view) returns null – Stack Overflow[/url] [url=http://www.1sucai.cn/article/86826.htm]AndroidGUI27中findViewById返回null的快速解决办法[/url] – 玄机逸士的专栏 – 博客频道 – CSDN.NET 但是没搞定。 [b]2.后来是去搜:[/b] findViewById R.layout null 而最终找到并参考: [Android]inflate方法与 findViewById 方法区别 | LayoutInflater的inflate函数用法详解 – loyea – 博客园 去换为: LayoutInflater inflater = (LayoutInflater)tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout groupPollingAddress = (LinearLayout)inflater.inflate(R.layout.fragment_field_list, null); 即可。 [b]3.另外的,类似的:[/b] TextView tab1AllGroupPollingAddressLabel = (TextView) findViewById(R.id.lblVariable); 也是返回null,所以去换为: TextView tab1AllGroupPollingAddressLabel = (TextView) groupPollingAddress.findViewById(R.id.lblVariable); 即可。 [b]【总结】[/b] 此处findViewById返回为null,原因是: 没有在索要find的子view的Parent中去找 或者是: 当然的View下面,没有包含对应的想要找的view, 从而导致找不到,返回null。 [b]解决办法是:[/b] 找到要找的view的parent或root的view 再在父级的view中找你要的子view就可以了。 [b]常见的写法是:[/b]
LayoutInflater inflater = (LayoutInflater)tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout)inflater.inflate(R.layout.fragment_field_list, null);
其中是先去找到当前系统的Layout,然后实例化,然后在全局的view中再去找你的view就可以找到了。 [b]PS:Android 自定义view中findViewById为空的快速解决办法[/b] 网上说的都是在super(context, attrs);构造函数这里少加了一个字段,其实根本不只这一个原因,属于view生命周期的应该知道,如果你在自定义view的构造函数里面调用findViewById 铁定为空的,因为这个时候view还在初始化阶段,还没有添加到activity的XML布局上,所以你怎么调用都是没用的,解决办法就是把我们的findViewById方法换一个生命周期上面调用就OK了,比如我就是在
 protected void onAttachedToWindow() {
super.onAttachedToWindow();} 
上面调用的
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部