ListView與Adapter的應用
埋頭苦幹研究了一星期 Custom ListView的使用,今天總算有點比較清晣。
為免明天過後把總結忘記得一乾二淨,編寫博客是必須的
To set up a custom ListView (including of image and text), the list shown as below are necessary.
- Custom Class
- Custom Layout (For what you need to display for every row)
- Custom Adapter (Specifically use to handle the custom class data)
- Data
- 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.

浙公网安备 33010602011771号