【发布时间】:2019-04-02 16:13:06
【问题描述】:
我正在尝试使用一个 Activity 来显示我的数组中的一个随机对象。这个对象是从一个意图传入的。
我正在尝试为这些对象中的每一个使用一个图像,然后为正确的对象显示正确的图像。
到目前为止,我一直在使用 drawable 文件夹来保存我的图像,然后通过 XML 将它们加载进来,但这阻止了我为同一个 ImageView 使用多个图像。 我尝试使用 imageview.setImageResource(R.drawable.imagename);但由于某种原因,这似乎不喜欢加载。 在这种情况下,我是否需要为每个对象创建一个新活动?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(R.drawable.hacan);
image.setImageBitmap(imageToBitmapImage(message, image));
name.setText(message.getName());
}
字节转位图方法
public Bitmap imageToBitmapImage (Race message, ImageView image){
Bitmap bmp;
try {
FileInputStream in = new FileInputStream(message.getImageName());
BufferedInputStream buffer = new BufferedInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int input = buffer.read();
while (input != -1){
baos.write(input);
input = buffer.read();
}
byte[] bytes = baos.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
我所说的每个对象的类。
public class Race implements Serializable {
private String name;
private String imageName; //name of file within drawable
【问题讨论】:
-
您应该选择使用 setImageResource 或 setImageBitmap。关于您的 imageToBitmapImage 函数,您的 FileInputStream 将读取手机上您的应用程序文件夹中的数据,但无法读取您放入项目中的可绘制对象。你检查过你没有在那里记录一些异常吗?
-
@XavierFalempin 我现在检查了一下,它给出了一个未找到的文件。我可以将这些图像放在哪里以便我可以参考它们?我还是 Android 新手,如果这是一个基本问题,我深表歉意。
-
Svarr 答案应该可以,但您也可以在 pojo 中使用可绘制的 id 值作为 int 而不是名称