【Android】16.0 UI开发(七)——列表控件RecyclerView的点击事件实现

时间:2022-06-15 11:12:12

1.0 在各布局的基础上,修改ProvinceAdapter.java的代码:

package com.example.recyclerviewtest;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast; import java.util.List; public class ProvinceAdapter extends RecyclerView.Adapter<ProvinceAdapter.ViewHolder> {
private List<Province> mProvinceList;
private int resourceId; // 定义一个内部类ViewHolder,该类继承自RecyclerView.ViewHolder。
// 需要传入一个View参数,通常是RecyclerView子项最外层布局
static class ViewHolder extends RecyclerView.ViewHolder {
// ImageView provinceImage;
TextView provinceName;
View provinceView; public ViewHolder(View view) {
super(view);
provinceView = view;
provinceName = (TextView) view.findViewById(R.id.province_name);
}
} // 该构造函数作用是将数据源赋值给一个全局变量mProvinceList
public ProvinceAdapter(List<Province> provinceList) {
mProvinceList = provinceList;
} // 由于ProvinceAdapter是继承自RecyclerView.Adapter,
// 所以需要重写三个方法:
// onCreateViewHolder() :创建ViewHolder实例,将局部加载进来
// onBindViewHolder() :对RecyclerView子项数据进行赋值
// getItemCount() @Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.province_item,
viewGroup,
false);
final ViewHolder holder = new ViewHolder(view);
holder.provinceView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Province province = mProvinceList.get(position);
Toast.makeText(v.getContext(), "你点击了项" + province.getName(), Toast.LENGTH_SHORT).show();
}
}); return holder;
} @Override
public void onBindViewHolder(ViewHolder holder, int position
) {
Province province = mProvinceList.get(position);
holder.provinceName.setText(province.getName());
} @Override
public int getItemCount() {
return mProvinceList.size();
}
}

2.0 列表控件RecyclerView没有提供直接可以调用的注册监听事件,需要我们给子项具体的View去注册点击事件。优点是可以在某一个子项中,点击其中的某个图片、字段、按钮等,而不像setOnItemClickListener()方法那样只能选择子项本身。