編輯:對不起,我從您的評論中意識到我的問題還不夠清楚。我會發佈一個新的。對不起,並感謝您的回答以編程方式將背景設置爲背景
我從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」需要繪製的參數。 「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"}]
可能你想使用setImageResources這需要一個int作爲參數,並設置你的imageview的src。仍然問題不是setBackgroundDrawable實現的。此外你的代碼不能worlìk。 ll不包含textview和imageview – Blackbelt
e1是什麼意思? json數據中的圖像在哪裏? – Oam
你可以發佈「資源」佈局 – Blackbelt