从动态位图中调整 AlertDialog 图标的大小

Resize an AlertDialog Icon from Dynamic BitMap

从 Android 19 (KITKAT) 开始,我无法再在代码中动态调整 AlertDialog 中图标的大小。它在 Android 8 - 16 期间有效。现在,它只显示图标的原始宽度和高度——而不是调整后的图标。

请注意,这些图像是从我的服务器上动态下载的,同一对话框会根据用户的选择显示不同的图像。

以下是我曾经使用过的方法。关于如何为 Android 19+ 更新它有什么建议吗?

注意:我已尝试 Bitmap.createScaledBitmap 解决方案(请参阅注释掉的行)。没有效果。

Uri downloadedIcon = Uri.parse( "file://" + filePath );
BitMap bm = Media.getBitmap( getContentResolver(), downloadedIcon );

DisplayMetrics metrics = new DisplayMetrics();        
getWindowManager().getDefaultDisplay().getMetrics(metrics);  
int width = metrics.widthPixels;

if (width >= 2000) {
    bm.setDensity(840);
    //bm = Bitmap.createScaledBitmap(bm,920,920,true);
} else if (width >= 1440) {
    bm.setDensity(640);
    //bm = Bitmap.createScaledBitmap(bm,700,700,true);
} else if(width >= 1024)
    // etc
}

BitmapDrawable icon = new BitmapDrawable(bm);

AlertDialog theAlert = new AlertDialog.Builder(MyActivity.this)
.setTitle("My Title")
.setMessage("My Description")
.setIcon(-1).setIcon(icon)
theAlert.show();

好的,我通过创建自己的对话框布局解决了这个问题。

问题是在Android 19+中,默认(系统)对话框布局会强制缩小图标的src。所以要让它变大——你需要忘掉图标,停止使用它。相反,在您自己的自定义布局中定义一个新的 ImageView。

custom_dialog.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <RelativeLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/dialog_pic"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitStart"
            android:adjustViewBounds="true" />

    </RelativeLayout>   

    <TextView 
        android:id="@+id/desc"
        android:text="DESCRIPTION GOES HERE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:typeface="serif"
        android:textSize="17sp" />  

</LinearLayout>

膨胀 ImageView 后,我用我的动态 BitMap 覆盖它,如下所示:

Uri downloadedIcon = Uri.parse( "file://" + filePath );
BitMap bm = Media.getBitmap( getContentResolver(), downloadedIcon );

View dialogView = getLayoutInflater().inflate(R.layout.my_custom_dialog, null);
ImageView pic = (ImageView) dialogView.findViewById(R.id.dialog_pic);
pic.setImageBitmap( bm );
TextView desc = (TextView) dialogView.findViewById(R.id.desc);
desc.setText("My Description Text");

AlertDialog theAlert = new AlertDialog.Builder(ScriptMenuActivity.this)
    .setView(dialogView)
    .setTitle("My Title Text")
    .setNegativeButton("Back", null)
    .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // do stuff
        }}).create();
    theAlert.show();

对话框图片通过 ImageView 的 'adjustViewBounds' 和 'scaleType' 属性自动按比例调整大小以适合对话框 window。