我有一门课
public class CountryVO {
private String countryCode;
private String countryName;
private Drawable countryFlag;
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Drawable getCountryFlag() {
return countryFlag;
}
public void setCountryFlag(Drawable countryFlag) {
this.countryFlag = countryFlag;
}
}
并希望将此类的对象存储在类似 android 的 TypeArray xml 中
<resources>
<array name="custom_arr">
<item>
<countryName>Albania</countryName>
<countryCode>al</countryCode>
<countryFlag>@drawable/al</countryFlag>
</item>
<item>
<countryName>Algeria</countryName>
<countryCode>dz</countryCode>
<countryFlag>@drawable/dz</countryFlag>
</item>
<item>
<countryName>American Samoa</countryName>
<countryCode>as</countryCode>
<countryFlag>@drawable/as</countryFlag>
</item>
<item>
<countryName>India</countryName>
<countryCode>in</countryCode>
<countryFlag>@drawable/in</countryFlag>
</item>
<item>
<countryName>South Africa</countryName>
<countryCode>sa</countryCode>
<countryFlag>@drawable/sa</countryFlag>
</item>
</array>
</resources>
我想如何在我的 Activty 类中访问这个数组,比如
TypedArray customArr = getResources().obtainTypedArray(R.array.country_arr);
CountryVO vo = new CountryVO();
vo.setCountryName(**value from array come here for first element's countryName attribute**);
vo.setCountryCode(**value from array come here for first element's countryCode attribute**);
vo.setCountryFlag(**value from array come here for first element's countryFlag attribute**);
但我不知道如何实现这一点。 我试过 customArr.getString(0);但它给了我一切都像字符串一样 阿尔巴尼亚 al @drawable/al
请帮我解决这个问题。
非常感谢,
谨此致以最诚挚的问候, 伊山
最佳答案
Here is example .阅读并查看 TypedArray 的方法,例如 get...()
,例如 getDrawable(int index)
。我建议将相同类型的项目保留在单独的数组中。
<array name="country">
<item>Albania</item>
<item>Algeria</item>
<item>American Samoa</item>
</array>
<array name="code">
<item>al</item>
<item>dz</item>
<item>as</item>
</array>
<array name="flag">
<item>@drawable/dz</item>
<item>@drawable/al</item>
<item>@drawable/as</item>
</array>
编辑:
public CountryVO getCountryVO(int index){
Resources resources = getResources();
TypedArray country = resources.obtainTypedArray(R.array.country);
TypedArray code = resources.obtainTypedArray(R.array.code);
TypedArray flag = resources.obtainTypedArray(R.array.flag);
CountryVO vo = new CountryVO(country.getString(index), code.getString(index), flag.getDrawable(index));
country.recycle();
code.recycle();
flag.recycle();
return vo;
}
关于android - Android 中的 TypeArray - 如何在 xml 中存储自定义对象并检索它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6774579/