关于Recycler工具类的设计
CommonRecyclerAdapter类
package com.example.example.util;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import java.util.Map;
public abstract class CommonRecyclerAdapter<T> extends RecyclerView.Adapter<CommonViewHolder> {
private List<T> dataList;
private Map<String,Integer> idMap;
private int itemLayout;
private Context context;
public CommonRecyclerAdapter(List<T> dataList, Map<String, Integer> idMap, int itemLayout, Context context) {
this.dataList = dataList;
this.idMap = idMap;
this.itemLayout = itemLayout;
this.context = context;
}
@NonNull
@Override
public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View embedView=View.inflate(context,itemLayout,null);
return new CommonViewHolder(embedView,idMap);
}
@Override
public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
T device=dataList.get(position);
paddingCallback(device,holder);
}
@Override
public int getItemCount() {
return dataList.size();
}
public abstract void paddingCallback(T t,CommonViewHolder holder);
}
CommonViewHolder类
package com.example.example.util;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.HashMap;
import java.util.Map;
public class CommonViewHolder extends RecyclerView.ViewHolder {
public Map<String, View> componentMap=new HashMap<>();
public CommonViewHolder(@NonNull View itemView,Map<String,Integer> idMap) {
super(itemView);
for (Map.Entry<String,Integer> entry:idMap.entrySet()){
componentMap.put(entry.getKey(),itemView.findViewById(entry.getValue()));
}
}
public <T> T getView(String tag){
return (T)componentMap.get(tag);
}
}
//主类的方法
private void createRecyclerView() {
//获取父布局,layout里面设置的androidx.recyclerview.widget.RecyclerView
RecyclerView recyclerView=findViewById(R.id.Recycler);
//创建一个map对象。用于存放item里面的控件,当前item里面只有两个控件,分别是TextView和ImageButton
Map<String,Integer> map=new HashMap<>();
//存入map容器中
map.put("TV_DI_CONTEXT",R.id.tv_di_context);
map.put("IB_DI_IMAGE",R.id.ib_di_image);
//给主布局设置适配器,传入四个参数,分别是数据的list对象,item存入map的控件,item的布局,以及当前类的context对象
recyclerView.setAdapter(new CommonRecyclerAdapter<User>(list,map,R.layout.recycle_di,this) {
@Override
public void paddingCallback(User user, CommonViewHolder holder) {
//取出对象
TextView textView=holder.getView("TV_DI_CONTEXT");
ImageButton imageButton=holder.getView("IB_DI_IMAGE");
textView.setText(user.getContext());
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(RecyclerTest.this));
}
item布局
主layout
优化之后的运行界面