ListView與Adapter的應用

埋頭苦幹研究了一星期 Custom ListView的使用,今天總算有點比較清晣。

為免明天過後把總結忘記得一乾二淨,編寫博客是必須的

To set up a custom ListView (including of image and text), the list shown as below are necessary.

  1. Custom Class
  2. Custom Layout (For what you need to display for every row)
  3. Custom Adapter (Specifically use to handle the custom class data)
  4. Data
  5. ListView

3. Custom Adapter's sample

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;
    public FruitAdapter (Context context, int textViewResourceId, List<Fruit> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
        ImageView fruit_image = (ImageView) view.findViewById(R.id.fruit_image);
        TextView fruit_name = (TextView) view.findViewById(R.id.fruit_name);
        fruit_image.setImageResource(fruit.getImageId());
        fruit_name.setText(fruit.getName());
        return view;
    }
}

If you need to get widget's ID from an non-current layout, you need to initialize a View by LayoutInflater and through it to find the ID.

//getContext() = current context, resourceId = target layout, inheriting from another layout
View view = LayoutInflater.find(getContext()).inflate(resourceId, null);
ImageView fruit_image = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruit_name = (TextView) view.findViewById(R.id.fruit_name);

Then, you can get its ID through the variable view to operate the findViewById method.

Otherwise, the widget's ID can't be recognized.

 

posted @ 2015-09-13 16:24  Troy.C  阅读(64)  评论(0)    收藏  举报