2013-05-16 112 views
11

編輯:對不起,我從您的評論中意識到我的問題還不夠清楚。我會發佈一個新的。對不起,並感謝您的回答以編程方式將背景設置爲背景

我從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"}] 
+0

可能你想使用setImageResources這需要一個int作爲參數,並設置你的imageview的src。仍然問題不是setBackgroundDrawable實現的。此外你的代碼不能worlìk。 ll不包含textview和imageview – Blackbelt

+0

e1是什麼意思? json數據中的圖像在哪裏? – Oam

+0

你可以發佈「資源」佈局 – Blackbelt

回答

39

試試這個

iv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.img)); 

iv.setBackgroundResource(R.drawable.img); 
+6

注意這隻適用於api 16+。 – CorayThan

+4

應該使用iv.setImageResource(R.drawable.img); – Brave

+0

@CorayThan如何在以前的API版本(<= 15)中實現這一點? – AnV

7

現在爲getDrawablesetBackgroundDrawable都是depricated你應該設置繪製的背景是這樣的:

view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable)); 

,如果你是16歲以下 targating 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)); 
    } 
0

這裏新的Metho d

recyclerView.setBackgroundResource(R.drawable.edit_text_button_shape);

不要使用它這是一個古老的方法 recyclerView.setBackgroundDrawable(this.getResources()。getDrawable(edit_text_button_shape));

相關問題