gpt4 book ai didi

java - 从任意类获取Android资源值

转载 作者:行者123 更新时间:2023-12-01 13:08:53 24 4
gpt4 key购买 nike

我刚刚开始学习 Android 编程,对一些概念仍然有点困惑。我将使用一个简化的示例告诉您我正在尝试做什么:

我正在从远程服务器 (PHP/MySQL/JSON) 检索汽车列表,并将它们显示在 ListView 上。

这是服务器响应JSON结构:

{
error: null,
data: {
cars: [
{name: "Lamborghini Diablo", color_id: 1},
{name: "McLaren F1", color_id: 2},
{name: "Ferrari F355", color_id: 1}
]
}
}

然后我编写了Car类:

public class Car {

public String name;
public int color_id;
public String color_name;

public Car(JSONObject data) {
try {
this.name = data.getString("name");
this.color_id = data.getInt("color_id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}

最后,这是 strings.xml 资源文件的一部分:

<string-array name="color_names">
<item>White</item>
<item>Yellow</item>
<item>Orange</item>
<item>Red</item>
<item>Black</item>
</string-array>

当我从服务器获取数据时,有一个 for循环创建 Car 类的实例,JSONArray 中的每一项都有一个实例。 .

我想要做的是从 <string-array> 获取颜色名称,使用属性 color_id作为数组索引,但我找不到获取 R.array 的方法资源来自Car类构造函数。

我应该怎么做?

谢谢!

最佳答案

What I want to do is to get the color name from the , using the property color_id as the array index, but I can't find a way to get the R.array resource from the Car class constructor.

你的类必须了解“关于上下文”因为资源只能从上下文中获取,所以这里你需要在构造函数中进行一些修改:

public Car(Context c, JSONObject data) {
// do your stuff
}

现在,您的类知道当前的上下文,因此您能够获取所需的数据:

String name = c.getResources().getStringArray(R.id.arrayId)[<index>];

希望能解决您的问题。

关于java - 从任意类获取Android资源值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com