如何在 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/