转自:http://stackoverflow.com/questions/1691569/findviewbyid-returns-null-for-custom-component-in-layout-xml-not-for-other-co
I have ares/layout/main.xml
including 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,butfoo
comes 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 isfoo
null?
解决方法:
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. :-)
原文地址:https://www.jb51.cc/xml/296889.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。