[英]Set image in other layout in android
I run on MainActivity
and I have firstshow.xml
with image imageView
( imshow
) and I use Inflater
to show it on dialog with this code 我上运行
MainActivity
和我有firstshow.xml
与图像imageView
( imshow
),我用Inflater
表明它在对话与此代码
ImageView fistTimeImv =(ImageView)findViewById(R.id.imshow);
fistTimeImv.setImageResource(R.drawable.first1);
AlertDialog.Builder dialog = new AlertDialog.Builder(
MainActivity.this);
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View view = factory.inflate(R.layout.firstshow, null);
dialog.setView(view);
dialog.show();
The above code throws NullPointerException
in the following line 上面的代码在下一行中引发
NullPointerException
fistTimeImv.setImageResource(R.drawable.first1);
So if I understand you correctly you want to inflate a View
from xml and set that View
on a Dialog
but you are getting a NullPointerException
when attempting to do so. 因此,如果我正确理解了您想从xml扩展一个
View
并在一个Dialog
上设置该View
,但是尝试这样做时会收到NullPointerException
异常。 To fix that you have to reorder your code as the following: 要解决此问题,您必须按以下步骤对代码重新排序:
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View view = factory.inflate(R.layout.firstshow, null);
ImageView fistTimeImv =(ImageView) view.findViewById(R.id.imshow); //Make sure to call findViewById on the view you just inflated
fistTimeImv.setImageResource(R.drawable.first1);
AlertDialog.Builder dialog = new AlertDialog.Builder(
MainActivity.this);
dialog.setView(view);
dialog.show();
There are two changes here: The first change is inflating your view
before finding the ImageView
. 这里有两个更改:第一个更改是在找到
ImageView
之前ImageView
view
。 If your ImageView
is a child element of your firstshow
layout then that layout needs to be inflated (built) first. 如果您的
ImageView
是firstshow
布局的子元素,则需要首先firstshow
(构建)该布局。 The second change is making sure that you try to find your ImageView
from the newly inflated view
. 第二个更改是确保尝试从新
view
查找ImageView
。 If you don't have view.findViewById(R.id.imshow);
如果您没有
view.findViewById(R.id.imshow);
you will try to find the ImageView
on whatever class
you are currently working in which probably isn't what you want. 您将尝试在当前正在使用的任何
class
上找到ImageView
,而这些class
可能不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.