TypeArray in Android - How to store custom objects in xml and retrieve them?

后端 未结 3 1557
逝去的感伤
逝去的感伤 2020-12-05 10:41

I have a class like

public class CountryVO {
    private String countryCode;
    private String countryName;
    private Drawable countryFlag;

    public St         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-05 11:29

    Here is example. Read it and look at the methods of TypedArray like get...() for example getDrawable(int index). I would suggest to keep items of the same type in separated arrays.

    
        Albania
        Algeria
        American Samoa
    
    
        al
        dz
        as
    
    
        @drawable/dz
        @drawable/al
        @drawable/as
    
    

    EDIT:

    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;
    }
    

提交回复
热议问题