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


【问题描述】

Android中如下代码:

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

返回为null。

【解决过程】

1.参考:

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

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就可以找到了。

PS:Android 自定义view中findViewById为空的快速解决办法

网上说的都是在super(context, attrs);构造函数这里少加了一个字段,其实根本不只这一个原因,属于view生命周期的应该知道,如果你在自定义view的构造函数里面调用findViewById 铁定为空的,因为这个时候view还在初始化阶段,还没有添加到activity的XML布局上,所以你怎么调用都是没用的,解决办法就是把我们的findViewById方法换一个生命周期上面调用就OK了,比如我就是在

 protected void onAttachedToWindow() {
super.onAttachedToWindow();} 

上面调用的


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3