编辑:非常抱歉,我从您的评论中意识到我的问题不够清晰。我会发表一个新的问题。对此我感到很抱歉,谢谢您的回答。
我正在使用 Json 文件填充 ListView。
通过我的 listadapter,我可以轻松地为列表的每一行分配适当的 json 数据。这对于文本非常有效,例如:
TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
使用上述代码,每一行都将被正确地填充为正确的JSON数据。
然而,我无法对图像执行相同的操作。 我尝试使用以下方法从我的JSON数据中设置正确的图像:
ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
我猜我在参数类型上做错了什么:“setBackgroundDrawable”需要一个drawable参数,“getDrawable”需要一个int参数。我已将我的img字段的类型设置为int,但这并不起作用。
有任何想法吗?
我的列表适配器:
public class adapter extends ArrayAdapter<ListItems> {
int resource;
String response;
Context context;
//Initialize adapter
public ListItemsAdapter(Context context, int resource, List<ListItems> items) {
super(context, resource, items);
this.resource=resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
//Get the current object
ListItems i = getItem(position);
//Inflate the view
if(convertView==null)
{
ll = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater)getContext().getSystemService(inflater);
li.inflate(resource, ll, true);
}
else
{
ll = (LinearLayout) convertView;
}
//For the message
TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
// For the Img
ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
return ll;
}
我的物品类别:
public class ListItems{
int id;
int img;
String desc;}
这是我的 JSON 文件示例:
[{"id":10001,"img":e1,"desc":"desc1"},
{"id":10002,"img":e2,"desc":"desc2"},
{"id":10003,"img":e3,"desc":"desc3"}]