findViewById() returns null for custom component in layout XML, not for other components

前端之家收集整理的这篇文章主要介绍了findViewById() returns null for custom component in layout XML, not for other components前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

原文链接:https://www.f2er.com/xml/296889.html

猜你在找的XML相关文章