背景
在使用RecyclerView时,经常需要针对特定的页面写viewHolder,相当繁琐。后来看到项目中采用了统一通用的viewHolder,使用相当简单。为了更加通用,对原有代码进行了抽象简化,做成了一个依赖库,直接调用即可。
先上效果图:
开源代码地址(一共四个类):
https://github.com/cxyzy1/commonViewHolder
通用adapter基础类:BaseCommonAdapter
多布局通用adapter:MultipleCommonAdapter
单布局通用adapter:SimpleCommonAdapter
通用viewHolder:ViewHolder
使用方法:
工程根目录下build.gradle文件添加:
allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
app工程下build.gradle文件添加依赖:
dependencies { implementation 'com.github.cxyzy1:commonViewHolder:0.0.2' }
调用样例:
List<String> data = prepareData(); RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(prepareAdapter(data));private SimpleCommonAdapter<String> prepareAdapter(List<String> data) { return new SimpleCommonAdapter<String>(data, android.R.layout.simple_list_item_1) { @Override protected void onBindViewHolder(ViewHolder holder, String data, int position) { holder.setText(android.R.id.text1, data) .setTextColor(android.R.id.text1, Color.RED) .setOnItemClickListener((view) -> Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show() ); } }; } private List<String> prepareData() { List<String> data = new ArrayList<>(100); for (int i = 0; i < 100; i++) { data.add("text-" + i); } return data; }
作者:程序园中猿
链接:https://www.jianshu.com/p/4670ca0ae832