Android:如何从数据库设置AlertDialog的图标?

3

所以我正在展示类似于这样的AlertDialog:

new AlertDialog.Builder(context)
  .setMessage(message)
  .setTitle(title)
  .setCancelable(true)
  .setIcon(R.drawable.ic_launcher) // set icon
  // more code

是否可能使用setIcon方法从数据库中获取图标,例如联系人照片?

DatabaseHelper db = new DatabaseHelper(context);        
Cursor csr = db.getSpecialContact(number);
csr.moveToFirst();
String photo = csr.getString(csr.getColumnIndexOrThrow("photo_url"));
Uri photo_url = Uri.parse(photo);

我希望能够使用photo_url(保存在数据库中,如content://com.android.contacts/data/1)并将其与setIcon一起使用,但当然它期望参数是int而不是stringUri。请问这可以实现吗?

2个回答

4
这是如何实现的:
Drawable drawable = null;

try {

    DatabaseHelper db = new DatabaseHelper(context);
    Cursor csr = db.getSpecialContact(number);
    csr.moveToFirst();
    String photo = csr
        .getString(csr.getColumnIndexOrThrow("photo_url"));
    Uri photo_url = Uri.parse(photo);

    Bitmap tempBitmap;
    tempBitmap = BitmapFactory.decodeStream(context
        .getContentResolver().openInputStream(photo_url));

    // Convert bitmap to drawable
    drawable = new BitmapDrawable(context.getResources(), tempBitmap);

} catch (FileNotFoundException e) {
    Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
        R.drawable.ic_launcher);
    drawable = new BitmapDrawable(context.getResources(), bm);
}

new AlertDialog.Builder(context)
    .setMessage(message)
    .setTitle(title)
    .setCancelable(true)
    .setIcon(drawable)

1
例如,您可以使用BitmapDrawable或任何其他Drawable的子类。
BitmapDrawable drawable = new BitmapDrawable(bitmap);

AlertDialog.Builder builder = new AlertDialog.Builder(context)
  .setMessage(message)
  .setTitle(title)
  .setCancelable(true)
  .setIcon(drawable);

你可以直接在构造函数中使用InputStreamBitmapDrawable提供数据。但是,您首先必须创建一个Bitmap实例或InputStream。如何创建取决于您如何存储图像。

如何使用从数据库中获取的内容与 BitmapDrawable 结合使用?您能否更详细地说明一下您的示例?谢谢。我认为构造函数 BitmapDrawable 不支持参数。 - Dev01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接