1

例如,如果我要創建約類食品的自定義列表視圖,在每個LIST_ITEM由食品類標誌,食品類的名字。如果我將食物類型名稱存儲在字符串資源中並將每種食物類型的圖片存儲在drawable中。如何自定義每個項目視圖與圖像從繪製?

1)如何從繪製得到的圖片,並設置到列表視圖? 2)如何獲得提前匹配名稱食物類型的

感謝您的圖片。

public class FoodListActivity extends ListActivity { 

    private CustomListAdapter listAdapter; 
    private String[] food_type_name; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.foodlistholder); 

     food_type_name = getResources().getStringArray(R.array.food_name_array); 


     listAdapter = new CustomListAdapter(this, R.layout.list_item_food, food_type_name); 



     setListAdapter(listAdapter); 


    private class CustomListAdapter extends ArrayAdapter<String>{ 

     private String[] items; 

     public CustomListAdapter(Context context, int textViewResourceId, 
       String[] items) { 
      super(context, textViewResourceId, items); 
      this.items = items; 
     } 


     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View v = convertView; 
      if(v == null){ 
       LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       v = vi.inflate(R.layout.list_item_food, null); 
      } 

      TextView foodNameStr = (TextView)v.findViewById(R.id.food_name_txt); 

      foodNameStr.setText(items[position]); 
       //How to set Image view form drawable, which match the food's type name 

     return v; 


    } 

    } 

} 
+1

更好的通過這個例子http://www.vogella.de/articles/AndroidListView/article.html – 2012-01-06 11:34:27

+0

感謝您的雁,不過,我認爲會有一些更漂亮的解決方案去。以下該鏈接,它只有2圖像(R.drawable.no和R.drawable.ok)如果/ ESE條件來切換2圖像用它。如果,我有很多類型的食物可能是40個清單項目。我是否需要寫一個條件來切換全部40個項目?如果是這樣我會做一個開關盒。無論如何,謝謝你 – 2012-01-06 12:34:52

回答

2

就像你通過設置文本,但爲一個ImageView。

ImageView foodPhoto = (ImageView)v.findViewById(R.id.food_photo); 
foodPhoto.setImageDrawable(foodDrawable); 

你只需要創建一個可繪製的id列表來知道使用哪個drawable。