最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Android中findViewById返回为空null

Android crifan 9201浏览 0评论

【问题】

Android中如下代码:

LinearLayout groupPollingAddress = (LinearLayout)findViewById(R.layout.fragment_field_list);

返回为null。

【解决过程】

1.参考:

android – getActivity().findViewById(R.layout.contacts_list_view) returns null – Stack Overflow

findViewById返回空指针的解决方法_重拾旧梦_百度空间

AndroidGUI27:findViewById返回null的解决办法 – 玄机逸士的专栏 – 博客频道 – CSDN.NET

但是没搞定。

2.后来是去搜:

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);

即可。

3.另外的,类似的:

TextView tab1AllGroupPollingAddressLabel = (TextView) findViewById(R.id.lblVariable);

也是返回null,所以去换为:

TextView tab1AllGroupPollingAddressLabel = (TextView) groupPollingAddress.findViewById(R.id.lblVariable);

即可。

 

【总结】

此处findViewById返回为null,原因是:

没有在索要find的子view的Parent中去找

或者是:

当然的View下面,没有包含对应的想要找的view,

从而导致找不到,返回null。

解决办法是:

找到要找的view的parent或root的view

再在父级的view中找你要的子view就可以了。

常见的写法是:

LayoutInflater inflater = (LayoutInflater)tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout)inflater.inflate(R.layout.fragment_field_list, null);

其中是先去找到当前系统的Layout,然后实例化,然后在全局的view中再去找你的view就可以找到了。

转载请注明:在路上 » 【已解决】Android中findViewById返回为空null

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. 你的总结看不懂啊亲~ 不要写的这么晦涩难懂啊
    杨医生9年前 (2015-09-19)回复
86 queries in 0.196 seconds, using 22.15MB memory