ListView
基本用法
1.创建一个Item类,里面存储的是一条Item的信息
public Fruit{
private String name;
private int id;
...
}
2.创建一个Item的Adapter 继承ArrayAdapter<>并且重载其构造函数和getView方法
public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> fruits) {
super(context, resource, fruits);
resourceId = resource;
}
上面代码中resource应该是item布局的resource 用于后面查找到单个条目的view并且对其进行操作
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Fruit fruit = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName());
return view;
}
上面的getView是为了构建每一个条目的视图,通过inflate 获取了视图的实体
并且通过findViewById获取控件的实体进行设置
最终返回view
4.创建Item的布局
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
5.在父界面中找到ListView的实体并且为其设置Adapter
ListView listView = findViewById(R.id.lvFruitList);
listView.setAdapter(new FruitAdapter(this, R.layout.fruit_item, getList()));
其中FruitAdapter构造方法的第二个参数是Item布局的id
提升效率
使用简单的方法实现的ListView的效率较低,所以有一些改进效率的措施
1
在getView界面中判断传入的参数convertView是否为空,如果是空的话,就通过Inflater获取,否则的话,直接复用convertView
if(convertView!=null){
view = convertView;
}else{
view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
}
这一步是为了减少view绑定的次数
2 继续优化
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView != null) {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
} else {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = view.findViewById(R.id.fruit_name);
view.setTag(viewHolder);
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
这一步是为了减少资源绑定的次数
但是具体为什么可以这么用,不太清楚,后面有机会看看源码
点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: " + position);
}
});
标签:viewHolder,fruit,convertView,ListView,id,view
From: https://www.cnblogs.com/baidurenshen/p/17754378.html