1

我正在尝试使用Drawable对象创建自定义通知栏,但它不会Drawable在参数中接收,仅Bitmap.

问题:

我需要在我的通知中设置另一个应用程序的图标。我尝试使用下面的代码:

getPackageManager().getApplicationIcon(packageName);//Return a Drawable Object

//Problem
Notification.Builder builder = new Notification.Builder(context);
builder.setLargeIcon(Bitmap); //I don´t have this one, only a Drawable object.

如你看到的。如何使用此对象放入我的通知栏?

预期结果:

使用另一个应用程序的图标、名称和此应用程序的操作创建一个通知栏。

解决方案:

谢谢,pietmau 和 kadrei。

请使用以下代码:

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

并完成这个:

Notification.Builder builder = new Notification.Builder(context);

Drawable icon = getPackageManager().getApplicationIcon(
                packageName);
Bitmap bitmapIcon = drawableToBitmap(icon);

builder.setIcon(android.R.drawable.stat_sys_download_done).//It´s necessary put a resource here. If you don´t put any resource, then the Notification Bar is not show.
setLargeIcon(bitmapIcon);

Notification notification = builder.getNotification();
notificationManager.notify(yourId, notification);
4

2 回答 2

1

也许这有帮助:

public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
    return ((BitmapDrawable)drawable).getBitmap();
}

int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;

Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); 
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

return bitmap;
}

来源: https ://stackoverflow.com/a/9390776/1955332

于 2013-02-26T19:45:27.217 回答
1
 Bitmap= BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.drawable);

编辑 编辑 编辑

那么试试这个:

    public static Bitmap drawableToBitmap (Drawable drawable) {
       if (drawable instanceof BitmapDrawable) {
           return ((BitmapDrawable)drawable).getBitmap();
       }

       int width = drawable.getIntrinsicWidth();
       width = width > 0 ? width : 1;
       int height = drawable.getIntrinsicHeight();
       height = height > 0 ? height : 1;

       Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
       Canvas canvas = new Canvas(bitmap); 
       drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
       drawable.draw(canvas);

       return bitmap;
    }
于 2013-02-26T19:31:22.593 回答