Android Studio File Templates for RecyclerView Adapter

参考资料

LiveTemplate for RecyclerView Adapter

操作步骤

1
Settings | Editor | File and Code Templates

添加模板文件,命名为 RecyclerView Adapter

模板代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;

#parse("File Header.java")
public class ${NAME} extends
RecyclerView.Adapter<${NAME}.ItemViewHolder> {

private Context context;
private List<${ITEM_TYPE}> dataSet;
private View.OnClickListener onItemClickListener;

${NAME}(Context context, View.OnClickListener onItemClickListener) {
this.context = context;
this.onItemClickListener = onItemClickListener;
}

${ITEM_TYPE} getItemData(int position) {
return dataSet.get(position);
}

void setDataSet(List<${ITEM_TYPE}> dataSet) {
this.dataSet = dataSet;
notifyDataSetChanged();
}

@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(context), parent);
}

@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
${ITEM_TYPE} item = dataSet.get(position);
holder.bind(item);
}

@Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
}

class ItemViewHolder extends RecyclerView.ViewHolder {
ItemViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.${item_layout}, parent, false));
}

void bind(${ITEM_TYPE} model) {
itemView.setOnClickListener(onItemClickListener);
}
}
}