findViewById()在布局XML中为自定义组件返回null,而不是其他组件

我有一个res / layout / main.xml包括这些元素和其他:
<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />

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

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(…)在构造函数的末尾成功地出现在logcat就在“史诗失败”之前。

为什么是foo null?

因为在构造函数中,我有super(context)而不是super(context,attrs)。

有意义的,如果你不传入的属性,如id,那么视图将没有id,因此不能找到使用该id。

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念