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

findViewById() returns null for custom component in layout X

发布时间:2020-12-16 09:11:10 所属栏目:百科 来源:网络整理
导读:转自:http://stackoverflow.com/questions/1691569/findviewbyid-returns-null-for-custom-component-in-layout-xml-not-for-other-co I have a res/layout/main.xml including these elements and others: some.package.MyCustomView android:id = "@+id/f

转自:http://stackoverflow.com/questions/1691569/findviewbyid-returns-null-for-custom-component-in-layout-xml-not-for-other-co


I have ares/layout/main.xmlincluding these elements and others:

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

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"); }

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

Why isfoonull?



解决方法:

Because in the constructor,I hadsuper(context)instead ofsuper(context,attrs).

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. :-)

(编辑:李大同)

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

    推荐文章
      热点阅读