我想知道一种将图像和相关文本存储在类似列表中的方法。我试着做这样的事情
List<NameValuePair>cars = new ArrayList<NameValuePair>();
cars.add(new BasicNameValuePair("Hyundai Elantra",Integer.toString(R.drawable.hyundai_elantra)));
我知道这是错误的,但我发布它是为了让您了解我要实现的目标。
最佳答案
看起来对您来说最好的办法是创建一个名为 Car
的自定义类存储每辆车,然后创建一个 ArrayList<Car>
存储数据。
这是您的 Car 类的样子:
public class Car
{
public String type;
public int imageID;
public Car(String t, int i)
{
type = t;
imageID = i;
}
public String toString()
{
return type + " " + String.valueOf(imageID);
}
}
然后您将声明 ArrayList,并添加值:
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Hyundai Elantra", R.drawable.hyundai_elantra));
carList.add(new Car("Lexus RX350", R.drawable.lexus_rx350));
然后,您可以在想要填充 UI 时遍历列表:
for (Car c : carList){
String s = c.type;
int image = c.imageID;
//use the values.......
}
请注意,您可以将此 ArrayList 用作自定义适配器的数据源,以在 ListView 中显示文本和图像,如果您希望这样做的话。
关于android - 将图像和文本存储在一种数据类型android中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30282162/