加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 08:15:59 所属栏目:百科 来源:网络整理
导读:我有一个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.m
我有一个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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读