我有一个包含这些元素和其他元素的res/layout/main.xml
:
<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />
在我的活动的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"); }
成功找到其他元素,但foo
返回null。MyCustomView有一个构造器MyCustomView(Context c, AttributeSet a)
,该构造器结尾处的Log.d(...)
在“史诗失败”之前成功出现在logcat中。
为什么foo
为空?
发布于 2009-11-07 09:55:11
因为在构造函数中,我用super(context)
代替了super(context, attrs)
。
这是有道理的,如果您不传入属性,比如id,那么视图将没有id,因此无法使用该id进行查找。:-)
发布于 2011-02-01 21:59:17
我也有同样的问题。我的错误是:我写了
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout=inflater.inflate(R.layout.dlg_show_info, null);
alertDlgShowInfo.setView(layout);
TableRow trowDesc=(TableRow)findViewById(R.id.trowDesc);
当我使用充气器从XML文件中“加载”视图时,最后一行是错误的。为了解决这个问题,我不得不写道:
TableRow trowDesc=(TableRow)layout.findViewById(R.id.trowDesc);
我写下了我的解决方案,以防有人遇到同样的问题。
发布于 2011-03-24 21:57:10
似乎有各种各样的原因。我刚用了“干净...”在Eclipse中解决类似的问题。(FindViewByID以前工作过,但由于某种原因开始返回null。)
https://stackoverflow.com/questions/1691569
复制相似问题