将 ImageView 从一个活动传递到另一个活动 - Intent - Android



我的安卓应用程序的可绘制文件夹中有 170 张图像。我有一个活动显示所有这些。要做的是将单击的图像视图传递给另一个活动 (Zoom_activity),用户可以在其中缩放它并使用它。我如何实现它?

所有图像均为500x500像素。所以我无法想到将它们解码为位图并通过意图传递 Btmap。请提出一个更好,更简单的方法!我已经在SO上查看了其他答案,但没有一个可以解决我的问题。

这是我的代码:

Activity_1.java

Intent startzoomactivity = new Intent(Activity_one.this, Zoom_Image.class);
String img_name = name.getText().toString().toLowerCase(); //name is a textview which is in refrence to the imageview.
startzoomactivity.putExtra("getimage", img_name);
startActivity(startzoomactivity);

Zoom_Activity.java

    Intent startzoomactivity = getIntent();
    String img_res = getIntent().getStringExtra("getimage");
    String img_fin = "R.drawable."+img_res;
    img.setImageResource(Integer.parseInt(img_fin));

错误:应用强制关闭

请帮我解决这个问题!
谢谢!

Integer.parseInt()仅适用于像"1"或"123"这样的字符串,这些字符串实际上只包含整数的字符串表示形式。

您需要的是按名称查找可绘制资源。

这可以使用反射来完成:

String name = "image_0";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);

或使用Resources.getIdentifier()

String name = "image_0";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

你尝试的是错误的。您无法使用 Integer.parseInt 转换"R.drawable.name"。 Integer.parseInt 期待类似 "100" 的东西。你应该使用

getIdentifier(img_fin, "drawable", getPackageName()); 

检索要查找的资源 ID

使用 getResources().getIdentifier 在 ImageView 中从 Drawable 加载图像,如下所示:

int img_id = getResources().getIdentifier(img_res, "drawable", getPackageName());
img.setImageResource(img_id);

最新更新