以编程方式将可绘制对象设置为背景 [英] Set a drawable as background programmatically

查看:170
本文介绍了以编程方式将可绘制对象设置为背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我从您的评论中意识到我的问题不够清楚.我将发布一个新的.抱歉,谢谢您的回答

我正在从Json文件填充列表视图. 使用listadapter,我可以轻松地为列表的每一行分配适当的json数据.这对于文本效果很好,例如:

I am populating a listview from a Json file. With my listadapter, I can easily assign appropriate json data to each row of my list. That works well for text, for example:

TextView tv = (TextView)ll.findViewById(R.id.descView);   
tv.setText(i.desc);

使用上面的代码,正确的json数据将正确填充每一行.

With the above code, every row will be correctly populated by the good json data.

但是,我无法对图像执行相同的操作.我尝试使用以下方法从json数据中设置正确的图像:

However, I don't manage to do the same thing for an image. I have tried to set the right image from my json data using this:

ImageView iv = (ImageView)ll.findViewById(R.id.imgView);           
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));

我想我的参数类型做错了:"setBackgroundDrawable"需要一个drawable参数. "getDrawable"需要一个int. 我已将字段img的类型设置为int,但这不起作用.

I guess I am doing something wrong with the type of my parameters: "setBackgroundDrawable" requires a drawable parameter. "getDrawable" requires an int. I have set the type of my field img to int, but that doesn't work.

知道为什么吗?

我的列表适配器:

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文件的示例:

And a sample of my json file:

    [{"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);

这篇关于以编程方式将可绘制对象设置为背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆