从不同布局更改 ImageView 时的 Android NPE
我正在尝试使用代码等更改不同布局中的 ImageView:
ImageView imageView;
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(R.drawable.wizardhat);
但它在 R.drawable.wizardhat 上是 NPE,因为它显然不知道它属于什么布局,而且它不在根布局中:
-main [两个包含文件所在的位置]
-layout1[其中包含代码]
-layout2[图像所在位置]
编辑:好的,我并没有真正解释它:代码运行的视图位于选项卡视图内。保存选项卡视图的布局包含对包含我正在尝试编辑的 ImageView 的布局的包含。我没有正确地表达我的问题,我现在编辑它:L
这可能吗?谢谢 :)
I'm trying to change an ImageView in a different layout using code etc:
ImageView imageView;
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(R.drawable.wizardhat);
But it NPE's on R.drawable.wizardhat because it doesn't know what layout it belongs to, obviously, and it's not in the root layout:
-main [where both includes are located]
-layout1[where code is included]
-layout2[where image is located]
EDIT: Ok, I didn't really explain it: The view that the code runs in is inside a tabview. The layout that holds the tab view contains a include to a layout that contains a ImageView which i'm trying to edit. I didn't really word my question correctly, i'll edit it now :L
Is this possible? Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,它是在
imageView
上的 NPE,因为在膨胀任何视图之前,您应该将其根布局设置为 Activity 的内容视图。如果您的ImageView
属于layout1
,您必须确保它是 Activity 的当前内容视图,然后您可以从代码中的任何位置对其进行扩充。如果layout1
现在不是内容视图,findViewById()
将返回 null。我希望我已经正确理解了你的问题。Actually, it NPE's on
imageView
, cause before inflating any view you should set its root layout as a content view of your activity. If yourImageView
belongs tolayout1
, you must be sure that it is the current content view of the activity, then you can inflate it from wherever you want in your code. Iflayout1
is not the content view right now,findViewById()
will return null. I hope I've understood your question properly.我为我的应用程序所做的是:
您也许可以用它来解决您的问题。
What I did for my app were:
You could maybe use that for your issue.