no_profile
no_profile

Reputation: 374

How to display an image as a message in an Alert Dialog box?

I'm making a listview of marvel heroes that has an image, their real name and their superhero name. And every time I click a character in the list, I want to display an alert dialog box that will look like this without creating a custom layout?

PS: I'm a student and our instructor clearly instructed us not to create a custom layout.

enter image description here

Can someone please tell me how to achieve the image snippet above? Thanks! I have tried putting setIcon but it will just show the image as an icon on the upper left side of the box.

Here is my code so far:

MainActivity.java

<-- start of snippet -->

lv = (ListView) this.findViewById(R.id.listview1);
adapter = new CustomAdapter(this, list);

list.add(new Characters(R.drawable.thor, "Ordinson, Thor", "Thor"));
list.add(new Characters(R.drawable.steve, "Rogers, Steve", "Captain America"));
list.add(new Characters(R.drawable.stark, "Stark, Tony", "Ironman"));

lv.setAdapter(adapter);
builder = new AlertDialog.Builder(this);
builder.setNeutralButton("Okay", null);
lv.setOnItemClickListener(this);


@Override
public void OnItemClick(AdapterView<?> parent, View view, int position, long id){
     Characters selectedCharacters = this.list.get(position);

     int image = selectedCharacters.getImg();
     String name = selectedCharacters.getName();
     String supername = selectedCharacters.getSupername();

     ImageView iv = new ImageView(this);
     iv.setImageResource(image);

     builder.setTitle("" +name+ "\n" +supername);
     AlertDialog dialog = builder.create();
     dialog.show();
}

<-- end of snippet -->

Upvotes: 2

Views: 206

Answers (1)

SaadAAkash
SaadAAkash

Reputation: 3193

You can use setView() to add the ImageView inside your AlertDialog like this:

@Override
public void OnItemClick(AdapterView<?> parent, View view, int position, long id){
     Characters selectedCharacters = this.list.get(position);

     int image = selectedCharacters.getImg();
     String name = selectedCharacters.getName();
     String supername = selectedCharacters.getSupername();
     ImageView iv = new ImageView(this);
     iv.setImageResource(image);
     builder.setTitle("" +name+ "\n" +supername);
     AlertDialog dialog = builder.create();
     builder.setView(iv)
     dialog.show();
}

For the reference, head over to this link of the documentation.

Upvotes: 1

Related Questions