我正在使用一个android项目,我将一个活动中的图像名称发送到另一个活动,该图像已经在drawable文件夹中,我尝试使用下面显示的代码,但它不起作用。
当代码
时,它正常工作imageView.setImageResource(R.drawable.someimage);
但我希望在某些图片中显示一张图片,这些图片将由其他活动决定,所以我需要以下内容
imageView.setImageResource(R.drawable.getIntent().getStringExtra("icon"));
如何解决?
答案 0 :(得分:1)
您应首先获取资源ID。
Context context = imageView.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
imageView.setImageResource(id);
我认为在您的情况下resourceName
将是:
String resourceName = getIntent().getStringExtra("icon")
答案 1 :(得分:0)
您可以简单地将Int添加到您的Intent的Bundle中,以获取请求的图像资源:
intent.putExtra("icon", R.drawable.icon)
然后只使用它:
int imageResource = intent.getIntExtra("icon")
imageView.setImageResource(imageResource);
这更简单
答案 2 :(得分:0)
以下是解决方案
Context context = imageView.getContext();
int id = context.getResources().getIdentifier(getIntent().getStringExtra("icon"), "drawable",
context.getPackageName());
imageView.setImageResource(id);