2017-03-18 41 views
0

我想顯示帶有圖像的AlertDialog。但圖像可能會根據某些情況而改變。Android - 帶有可變圖像的警報對話框

這是我使用的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文件,所以我可以改變圖像?或者有更好的方法來做到這一點?

回答

0

你可以通過你的view調用findViewById得到ImageView的引用,然後調用setImageResource它:

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(); 
+0

謝謝!有效。 –