Don*_*Don 14 android json drawable
编辑:对不起,我从你的评论中意识到我的问题不够明确.我会发一个新的.对不起,谢谢你的回答
我正在从Json文件填充listview.使用listadapter,我可以轻松地将相应的json数据分配给列表的每一行.这适用于文本,例如:
TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,每个行都将由良好的json数据正确填充.
但是,我无法为图像做同样的事情.我试图使用以下方法从我的json数据中设置正确的图像:
ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
Run Code Online (Sandbox Code Playgroud)
我想我的参数类型有问题:"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;
}
Run Code Online (Sandbox Code Playgroud)
我的项目类:
public class ListItems{
int id;
int img;
String desc;}
Run Code Online (Sandbox Code Playgroud)
以及我的json文件的示例:
[{"id":10001,"img":e1,"desc":"desc1"},
{"id":10002,"img":e2,"desc":"desc2"},
{"id":10003,"img":e3,"desc":"desc3"}]
Run Code Online (Sandbox Code Playgroud)
pet*_*ter 44
试试这个
iv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.img));
Run Code Online (Sandbox Code Playgroud)
要么
iv.setBackgroundResource(R.drawable.img);
Run Code Online (Sandbox Code Playgroud)
Kap*_*put 12
现在getDrawable和你们setBackgroundDrawable两个都depricated应该像这样将drawable设置为Background:
view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
Run Code Online (Sandbox Code Playgroud)
如果你在16岁以下的地方跟踪minSdk然后做一个这样的检查:
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.your_drawable));
} else {
view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67508 次 |
| 最近记录: |