gpt4 book ai didi

android - 如何在 Activity 之间传递drawable

转载 作者:IT老高 更新时间:2023-10-28 21:54:42 27 4
gpt4 key购买 nike

如何在 Activity 之间传递图像、可绘制类型?

我试试这个:

private Drawable imagen;

Bundle bundle = new Bundle();
bundle.putSerializable("imagen", (Serializable) unaReceta.getImagen());
Intent myIntent = new Intent(v.getContext(), Receta.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);

但它向我报告了一个 execption:

java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable

最佳答案

1) 作为extras

传递intent

Activity A 中,您将图像解码并通过 Intent 发送:

  • 使用此方法(附加)图像在 162 毫秒的时间间隔内传递
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);     
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();

Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picture", b);
startActivity(intent);

Activity B 中,您会收到带有字节数组(解码图片)的 Intent ,并将其作为源应用到 ImageView:

Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("picture");

Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(bmp);

2)保存图像文件并将其引用传递给另一个 Activity

"The size limit is: keep it as small as possible. Definitely don't put a bitmap in there unless it is no larger than an icon (32x32 or whatever).

  • 在*Activity A* 中保存文件(内部存储)
String fileName = "SomeName.png";
try {
FileOutputStream fileOutStream = openFileOutput(fileName, MODE_PRIVATE);
fileOutStream.write(b); //b is byte array
//(used if you have your picture downloaded
// from the *Web* or got it from the *devices camera*)
//otherwise this technique is useless
fileOutStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
  • 将位置作为字符串传递给 Activity B
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picname", fileName);
  • 在 *Activity B* 中检索文件
Bundle extras = getIntent().getExtras();
String fileName = extras.getString("picname");
  • 让*drawable*脱离图片
File filePath = getFileStreamPath(fileName);
Drawable d = Drawable.createFromPath(filePath.toString());
  • 将其应用于 ImageView 资源
someImageView.setBackgroundDrawable(d);

关于android - 如何在 Activity 之间传递drawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8407336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com