【发布时间】:2012-01-06 11:27:53
【问题描述】:
例如,如果我必须创建有关食物类型的自定义列表视图,则在每个 list_item 中都包含食物类型徽标、食物类型名称。如果我将食物类型名称存储在字符串资源中,并将每种食物类型的图片存储在可绘制对象中。
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;
}
}
}
【问题讨论】:
-
感谢您的分析,但是,我认为会有一些更漂亮的解决方案。在该链接之后,它只有 2 个图像(R.drawable.no 和 R.drawable.ok),它使用 if/ese 条件来切换 2 个图像。如果,我有很多类型的食物可能是 40 列表项。我需要写一个条件来切换所有 40 个项目吗?如果是这样,我会做一个开关盒。无论如何,谢谢你
标签: android imageview android-listview android-arrayadapter custom-lists