android – 以可编程方式设置drawable作为背景

android – 以可编程方式设置drawable作为背景,第1张

概述编辑:对不起,我从你的意见中意识到我的问题不够清楚.我会发布一个新的.对不起,谢谢你的答案 我从一个Json文件填充一个listview. 使用我的listadapter,我可以轻松地将适当的json数据分配给我的列表的每一行.这对文本有用,例如: TextView tv = (TextView)ll.findViewById(R.id.descView); tv.setText(i.des 编辑:对不起,我从你的意见中意识到我的问题不够清楚.我会发布一个新的.对不起,谢谢你的答案

我从一个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 adapterpublic ListItemsAdapter(Context context,int resource,List<ListItems> items) {    super(context,resource,items);    this.resource=resource; }     @OverrIDepublic 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"}]
解决方法 尝试这个
iv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.img));

要么

iv.setBackgroundResource(R.drawable.img);
总结

以上是内存溢出为你收集整理的android – 以可编程方式设置drawable作为背景全部内容,希望文章能够帮你解决android – 以可编程方式设置drawable作为背景所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1131446.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存