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查找。

更多相关文章

  1. 按下子活动后退按钮后,Android主要活动的元素不响应
  2. Android:如何自动刷新UI上的元素(无需刷新整个屏幕)
  3. javaScript函数中执行C#代码中的函数
  4. JavaScript unshift()函数移入数据到数组第一位
  5. Java 8 新特性-菜鸟教程 (3) -Java 8 函数式接口
  6. 如何将动态参数传递给jquery函数
  7. Java多线程六:线程优先级和yield()让步函数
  8. dom4j-java-如何获取root中具有特定元素名称的所有元素(父元素或
  9. Selenium InternetExplorerDriver无法找到明显的元素。

随机推荐

  1. 序列化是什么意思
  2. 推荐10款ASP.NET过滤特效(收藏)
  3. XML的解析与创建范例
  4. xml编辑器哪个好?最好用的五款xml编辑工具
  5. 内容和属性用法的相关文章推荐
  6. Java中解析XML的方式有哪些
  7. 传智播客2017xml视频教程的课件源码分享
  8. XML是什么,有什么作用
  9. List集合的9篇内容推荐
  10. XML四大特性基础入门教程推荐