Android - 带有可变图像的警告对话框

Android - Alert Dialog with changeable image

我想显示带有图像的 AlertDialog。但图像可能会根据某些情况发生变化。

这是我用于 AlertDialog 的代码:

AlertDialog.Builder alertadd = new AlertDialog.Builder(wheel.this);
                    LayoutInflater factory = LayoutInflater.from(wheel.this);
                    final View view = factory.inflate(R.layout.alert, null);
                    alertadd.setView(view);
                    alertadd.setTitle("Alert Dialog Title");
                    alertadd.setNeutralButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });

                    alertadd.show();

这是 alert.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:id="@+id/dialog_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"/>

</LinearLayout>

有什么方法可以通过编程方式访问 XML 文件中的 imageView 以便我可以更改图像?或者有更好的方法吗?

您可以通过在 view 上调用 findViewById 然后在其上调用 setImageResource 来获得 ImageView 的引用:

LayoutInflater factory = LayoutInflater.from(wheel.this);
final View view = factory.inflate(R.layout.alert, null);

// change the ImageView image source
final ImageView dialogImageView = (ImageView) view.findViewById(R.id.dialog_imageview);
dialogImageView.setImageResource(R.drawable.your_image);    

alertadd.setView(view);
alertadd.setTitle("Alert Dialog Title");
alertadd.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {

        }
    });

alertadd.show();