无论如何在Android中将Drawable转换为int
Posted
技术标签:
【中文标题】无论如何在Android中将Drawable转换为int【英文标题】:Is there anyway to turn a Drawable to an int in Android 【发布时间】:2017-10-11 09:38:48 【问题描述】:我正在制作一个显示 android 设备已安装权限详细信息的应用。目前,我正在显示一个带有上述权限图标的 AlertDialog,但我也想根据用户的请求发送通知。我的代码是:
Drawable icon;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
String permission = getArguments().getString("permission");
String label = "";
String description = "";
icon = null;
try
label = getActivity().getPackageManager().getPermissionInfo(permission, PackageManager.GET_META_DATA).loadLabel(getActivity().getPackageManager()).toString();
description = getActivity().getPackageManager().getPermissionInfo(permission, PackageManager.GET_META_DATA).loadDescription(getActivity().getPackageManager()).toString();
icon = getActivity().getPackageManager().getPermissionInfo(permission, PackageManager.GET_META_DATA).loadIcon(getActivity().getPackageManager());
catch (Exception ignored)
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Permission")
.setMessage("Permission: " + getArguments().getString("permission") + Character.toString((char) 10) + "Label: " + label + Character.toString((char) 10) + "Description: " + description)
.setPositiveButton("Dismiss", null)
.setCancelable(false);
if (icon != null)
builder.setIcon(icon);
final AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setOnShowListener(new DialogInterface.OnShowListener()
@Override
public void onShow(DialogInterface dialog)
// Show notification here
);
return alertDialog;
但是,v4 NotificationCompat.Builder 不能将 Drawable 只取一个 int,我该怎么办?
【问题讨论】:
the v4 NotificationCompat.Builder can not take a Drawable only an int
。它需要 资源 id。结果是一个整数。
【参考方案1】:
您可以像这样获取图标资源 id(假设 permission
是您在问题中也使用的字符串):
final PackageManager pm = context.getPackageManager();
PermissionInfo info = pm.getPermissionInfo(permission, PackageManager.GET_META_DATA);
int iconResourceId = info.icon;
然后……
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(iconResourceId);
【讨论】:
【参考方案2】:R.drawable 是一个整数,R.color 或 R.string 或 R.layout 也是如此
【讨论】:
以上是关于无论如何在Android中将Drawable转换为int的主要内容,如果未能解决你的问题,请参考以下文章
如何在android中将状态栏背景设置为渐变色或drawable
在android中将drawable设置为浮动操作按钮ImageView
如何将 Android XML Drawable 保存、导出或转换为 PNG 图像文件?
Android:无法将@drawable/picture 转换为drawable