findViewById() 为布局 XML 中的自定义组件返回 null,而不是其他组件 [英] findViewById() returns null for custom component in layout XML, not for other components

查看:11
本文介绍了findViewById() 为布局 XML 中的自定义组件返回 null,而不是其他组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含这些元素和其他元素的 res/layout/main.xml:

I have a res/layout/main.xml including these elements and others:

<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />

在我的 Activity 的 onCreate 中,我这样做:

In my Activity's onCreate, I do this:

setContentView(R.layout.main);
TextView boring = (TextView) findViewById(R.id.boring);
// ...find other elements...
MyCustomView foo = (MyCustomView) findViewById(R.id.foo);
if (foo == null) { Log.d(TAG, "epic fail"); }

其他元素已成功找到,但 foo 返回 null.MyCustomView 有一个构造函数 MyCustomView(Context c, AttributeSet a) 和一个 Log.d(...) 构造函数末尾的 Log.d(...) 在 logcat 中成功出现在史诗般的失败".

The other elements are found successfully, but foo comes back null. MyCustomView has a constructor MyCustomView(Context c, AttributeSet a) and a Log.d(...) at the end of that constructor appears successfully in logcat just before the "epic fail".

为什么 foo 为空?

推荐答案

因为在构造函数中,我使用了 super(context) 而不是 super(context, attrs).

Because in the constructor, I had super(context) instead of super(context, attrs).

有道理,如果您不传入属性,例如 id,那么视图将没有 id,因此无法使用该 id 找到.:-)

Makes sense, if you don't pass in the attributes, such as the id, then the view will have no id and therefore not be findable using that id. :-)

这篇关于findViewById() 为布局 XML 中的自定义组件返回 null,而不是其他组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆