RecyclerView添加监听功能
程序员文章站
2022-06-14 13:43:00
...
通常我们在使用RecyclerView.Adapter时,需要给每个ViewHolder添加一个点击事件。我们可以为ForecastAdapter 类增添一个接口ForecastAdapterOnClickHandler 。并且我们修改ForecastAdapter的构造方法,将这个监听接口作为参数传递进来。
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> {
private String[] mWeatherData;
private final ForecastAdapterOnClickHandler mClickHandler;
public interface ForecastAdapterOnClickHandler {
void onClick(String weatherForDay);
}
public ForecastAdapter(ForecastAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public final TextView mWeatherTextView;
public ForecastAdapterViewHolder(View view) {
super(view);
mWeatherTextView = (TextView) view.findViewById(R.id.tv_weather_data);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
String weatherForDay = mWeatherData[adapterPosition];
mClickHandler.onClick(weatherForDay);
}
}
@Override
public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.forecast_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new ForecastAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(ForecastAdapterViewHolder forecastAdapterViewHolder, int position) {
String weatherForThisDay = mWeatherData[position];
forecastAdapterViewHolder.mWeatherTextView.setText(weatherForThisDay);
}
@Override
public int getItemCount() {
if (null == mWeatherData) return 0;
return mWeatherData.length;
}
public void setWeatherData(String[] weatherData) {
mWeatherData = weatherData;
notifyDataSetChanged();
}
下一篇: Vue 实现树形视图数据功能
推荐阅读
-
Android中RecyclerView拖拽、侧删功能的实现代码
-
android使用ItemDecoration给RecyclerView 添加水印
-
iOS Tabbar中间添加凸起可旋转按钮功能
-
如何给Android中的按钮添加图片功能
-
Android中RecyclerView实现Item添加和删除的代码示例
-
Android RecyclerView添加上拉加载更多效果
-
Android RecyclerView上拉加载更多功能回弹实现代码
-
Android编程实现添加低电流提醒功能的方法
-
Android中RecyclerView实现滑动删除与拖拽功能
-
Java程序中添加播放MIDI音乐功能的实现方法详解