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
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
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. 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
. If your ImageView
is a child element of your firstshow
layout then that layout needs to be inflated (built) first. The second change is making sure that you try to find your ImageView
from the newly inflated view
. If you don't have 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.