【发布时间】:2013-05-16 13:42:15
【问题描述】:
编辑:抱歉,我从您的评论中意识到我的问题不够清楚。我会发布一个新的。很抱歉,感谢您的回答
我正在从 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 作为参数并设置图像视图的 src。问题仍然不是 setBackgroundDrawable 的问题。你的代码也不能工作。 ll 不包含 textview 和 imageview
-
e1是什么意思?您的 json 数据中的图像在哪里?
-
你能发布“资源”布局吗
-
e1,e2,e3是你要设置的可绘制图片的名称吗?