android - 如何在 Activity 之间传递drawable

标签 android android-activity drawable

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

相关文章:

java - Firebase_Auth_API 在 API 23 上不可用

android - 主详细信息流程中的回调 'magic'

android - 我如何判断 Activity 何时停止与 App 何时停止?

android - Intent - startActivityForResult

android - 访问在主题和 attrs.xml android 中定义的资源

java - Android:尝试在空对象引用上调用虚方法 (onTouch)

android - AlarmManager Android 每天

java - Android - 调用自定义 View 方法时出现空指针异常

Android XML 可绘制透明渐变

Android菱形可绘制