【问题标题】:How to Custom each List item view with image from drawable?如何使用可绘制的图像自定义每个列表项视图?
【发布时间】: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


【解决方案1】:

就像您通过设置文本所做的那样,但对于 ImageView。

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

您只需要创建一个可绘制 id 的列表即可知道要使用哪个可绘制对象。

【讨论】:

    猜你喜欢
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多