只需对教程代码进行一些更改,您就可以做到这一点。
首先,在single_list_item_view.xml 中,您需要使用ImageView 而不是TextView,因为您要显示图像。您可以找到图像视图的文档,包括它们支持的属性,on the Android developer site。
其次,您需要更改查找TextView 的行以找到新的ImageView。这只需要更改以下行:
TextView txtProduct = (TextView) findViewById(R.id.product_label);
到:
// Assuming you gave your ImageView the id "product_image" in single_list_item_view.xml
ImageView productImage = (ImageView) findViewById(R.id.product_image);
您需要将要显示的图像添加到项目中。这些最简单的地方是res/drawable 文件夹。图像文件的名称将决定它们的“ids”。例如,如果您有res/drawable/photoshop.png,则可以使用 id R.drawable.photoshop 引用它。
接下来,您需要确定在SingleListItem 中显示哪个图像。单击列表中的项目如何显示其他内容的关键部分在SingleListItem:
Intent i = getIntent();
String product = i.getStringExtra("product");
相应地,在AndroidListViewActivity:
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
i.putExtra("product", product);
startActivity(i);
Intent 是您将信息从列表活动发送到显示项目的活动的方式。在这种情况下,发送的信息是要显示的项目。你有几个关于如何做这部分的选择。一种简单的方法是检查product 字符串并选择适当的drawable:
int imageId = -1;
if (product.equals("Adobe After Effects")) {
imageId = R.drawable.after_effects;
} else if (product.equals("Adobe Bridge")) {
imageId = R.drawable.bridge;
} else if ...
... // All your other cases
}
这种方法显然不能很好地扩展,但对于您的简单示例来说它可以正常工作。另一种可能的方法是在Intent 中传递图像ID,而不是产品名称,例如:
// In AndroidListViewActivity:
i.putExtra("product", R.drawable.after_effects);
// In SingleListItem:
int imageId = i.getIntExtra("product", -1);
// -1 in the call above is the value to return if "product" is not in the Intent
您需要做的最后一件事是为您之前找到的ImageView 设置Drawable:
// Make sure to check that the id is valid before using it
if (imageId != -1) {
Drawable d = getResources().getDrawable(imageId);
productImage.setDrawable(d);
}
getResources() 为您的应用程序获取 Resources 对象。您可以使用Resources 对象来查找您在res 文件夹中定义的字符串和可绘制对象等内容。您正在学习的教程还使用它在 res 文件夹中查找字符串数组。同样,您可以在 Android developer site 上看到 Resources 支持的所有内容。