Android通过Intent传图片
一、背景
在使用listView列表时,将图片文本存在列表中,点击列表或修改按钮时跳转到另一个活动页面显示图片。这时就需要取出图片,问题就此而来了。
二、遇到的问题
取出图片,直接对ImageView设置图片背景,不能显示。
三、解决方法
方式一(推荐):
取值:
private String[] context = {"乒乓球", "羽毛球", "网球"};
private int[] imageViews = {R.drawable.abd, R.drawable.abcd, R.drawable.absss};
private List<HashMap<String, Object>> list = new ArrayList<>();
Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
HashMap<String, Object> stringObjectHashMap = list.get(position);
ImageView imageView = view.findViewById(R.id.imageView);
// R.drawable.add ==> stringObjectHashMap.get("image").toString()
intent.putExtra("image", stringObjectHashMap.get("image").toString());
startActivity(intent);
取值:
String photo = getIntent().getStringExtra("image").toString();
Resources resources = this.getResources();
Drawable drawable = resources.getDrawable((int) Long.parseLong(photo));
imageView.setImageDrawable(drawable);
方式二:
注意:这种方式对API有要求,
存值
private String[] context = {"乒乓球", "羽毛球", "网球"};
private int[] imageViews = {R.drawable.abd, R.drawable.abcd, R.drawable.absss};
private Bitmap bitmap;
byte buff[] = new byte[125*250];
Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
HashMap<String, Object> stringObjectHashMap = list.get(position);
bitmap = BitmapFactory.decodeResource(getResources(), (Integer) stringObjectHashMap.get("image"));
buff = Bitmap2Bytes(bitmap);
intent.putExtra("image", buff);
startActivity(intent);
//放在外面
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
取值:
Intent mIntent = getIntent();
byte buff[]=mIntent.getByteArrayExtra("image");
Bitmap bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length);
BitmapDrawable mBitmapDrawable = new BitmapDrawable(bitmap);
//API16要求
imageView.setBackgroundDrawable(mBitmapDrawable);
如:
方式二不推荐。
本文来自博客园,作者:所遇所思,转载请注明原文链接:https://www.cnblogs.com/mynxg/p/17989303
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步