例如,如果我必须创建关于食物类型的自定义列表视图,则每个list_item包含食物类型徽标,食物类型名称。如果我将食物类型名称存储在字符串资源中并将每种食物类型的图片存储在drawable中。
1)如何从drawable获取图片并设置为List视图? 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;
}
}
}
答案 0 :(得分:2)
就像你设置文本一样,但对于ImageView。
ImageView foodPhoto = (ImageView)v.findViewById(R.id.food_photo);
foodPhoto.setImageDrawable(foodDrawable);
您只需要创建一个drawable ID列表,以了解要使用哪个drawable。