如何在警报对话框中将图像显示为消息?

时间:2019-06-30 04:37:00

标签: android listview alertdialog

我正在制作listview个具有图像,真实姓名和超级英雄姓名的惊奇英雄。而且,每当我单击列表中的一个字符时,我都想显示一个警告对话框,它看起来像这样,而无需创建自定义布局?

PS:我是一名学生,我们的老师明确指示我们不要创建自定义布局。

enter image description here

有人可以告诉我如何实现上面的图片片段吗?谢谢!我曾尝试将setIcon放进去,但是它只会在框的左上角将图像显示为图标。

到目前为止,这是我的代码:

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 -->

1 个答案:

答案 0 :(得分:1)

您可以使用setView()ImageView添加到AlertDialog内,如下所示:

@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();
}

作为参考,请转至本文档的link