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

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

问题描述

我有一个 RES /布局/ 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) />

在我活动的onCreate,我这样做:

In my Activity's onCreate, I do this:

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

其他的元素被成功找到,但回来空。 MyCustomView有一个构造 MyCustomView(上下文C,AttributeSet a)确定 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".

为什么空?

推荐答案

由于在构造函数中,我有超(上下文)而不是超(背景下,ATTRS)

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

是有道理的,如果你没有通过的属性,如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天全站免登陆