findViewById()返回布局XML中自定义组件的null,而不是其他组件
I have a res/layout/main.xml
including these elements and others:
我有一个res / layout /主要。xml包括这些元素和其他元素:
<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />
In my Activity's onCreate, I do this:
在我的活动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"); }
The other elements are found successfully, but foo
comes back null. MyCustomView has a constructor MyCustomView(Context c, AttributeSet a)
and a Log.d(...)
at the end of that constructor appears successfully in logcat just before the "epic fail".
其他元素被成功地找到,但是foo返回null。MyCustomView有一个构造函数MyCustomView(上下文c, AttributeSet a)和一个Log.d(…),在“epic fail”之前,该构造函数的末尾会在logcat中成功出现。
Why is foo
null?
为什么foo零?
18 个解决方案
#1
165
Because in the constructor, I had super(context)
instead of super(context, attrs)
.
因为在构造函数中,我使用了super(context)而不是super(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. :-)
有意义的是,如果您不传入属性,例如id,那么视图将没有id,因此不能使用该id查找。
更多相关文章
- 按下子活动后退按钮后,Android主要活动的元素不响应
- Android:如何自动刷新UI上的元素(无需刷新整个屏幕)
- javaScript函数中执行C#代码中的函数
- JavaScript unshift()函数移入数据到数组第一位
- Java 8 新特性-菜鸟教程 (3) -Java 8 函数式接口
- 如何将动态参数传递给jquery函数
- Java多线程六:线程优先级和yield()让步函数
- dom4j-java-如何获取root中具有特定元素名称的所有元素(父元素或
- Selenium InternetExplorerDriver无法找到明显的元素。