过去开发Android的时候,RecyclerView
是一个非常常用的类,但是RecyclerView.Adapter
却用起来有些麻烦,于是就根据需要写了很多XXXAdapter
之类的工具,也有很多开源可用的Adapter工具。如果只用一个,养成习惯后不成问题,但是如果比较多,就容易忘记或记错混淆。于是就有了一个想法:我能不能写一个不需要去记忆的工具,即便很长时间没用忘记了,也可以直接上手用。本文以NeoListAdapter
为例,来分享我的思考和实现方式。
注意:本文目标旨在分享一种通过建造者链达到类似“引导”的api组织方式,恰好是以NeoListAdapter
为例,如果你对使用/实现感到反感,那你是对的,因为NeoListAdapter
是根据我个人习惯随便写的
目标场景
我想要写一个工具类NeoListAdapter
用于取代ListAdapter
在一些简单的数据展示场景的使用,并且代码更加简洁,最重要的:不需要特别去记。
实现效果(使用过程)
先展示下最终的效果,以便说明为什么“不需要特别去记”。(大家可以把文章末尾NeoListAdapter
类复制到Android项目中,跟着下面的步骤操作,体会更深刻)
首先设想一个列表,里面要显示各种多媒体文件,包括音乐和视频。那么必然会有两个数据类:Music
和Video
,可能还都继承自Media
。与之对应的ViewHolder
自然是MusicHolder
和VideoHolder
。
为了让这些数据显示到RecyclerView
中,我们需要一个Adapter
,比如NeoListAdapter
。那么问题来了,假设我不知道如何构建NeoListAdapter
对象,也不知道它有哪些方法,正常情况这个时候就要去查文档和使用说明。但是,NeoListAdapter
这个工具的设计并需要看文档,而是让编辑器的提示来告诉我们怎么用。
步骤1
输入NeoListAdapter
,按下.
,我们能看到两个静态方法dataFrom
(接受数据list)和dataFor
(接受数据类型class)。没错,这就是一种提问:你想要为哪些数据构建Adapter/你想要为什么类型的数据构建Adapter?于是我们可以写下下面这样的代码:
NeoListAdapter.dataFrom(mediaList) // mediaList 为外部定义的 List<Media> 类型的对象
// 或
NeoListAdapter.dataFor(Media.class)
步骤2
再次按下.
,我们就看到了下面这些方法:
contentDiffBy(BiPredicate<T, T> contentSamePredicate)
:对应DiffUtil.ItemCallback
的areContentsTheSame
itemDiffBy(BiPredicate<T, T> itemSamePredicate)
:对应DiffUtil.ItemCallback
的areItemsTheSame
diffByDefault()
diffBy(DiffUtil.ItemCallback<T> itemCallback)
和diffBy(BiPredicate<T, T> itemSamePredicate, BiPredicate<T, T> contentSamePredicate)
也就是说,这一步提出的问题是:如何区别(diff)item?contentDiffBy
和itemDiffBy
对应ListAdapter
需要的DiffUtil.ItemCallback
的两个方法实现,其中diffByDefault
则表示使用equals
方法来实现。
于是我们可以写下下面这些代码:
NeoListAdapter.dataFor(mediaList).diffByDefault()
//或
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path))
步骤3
再次按下.
,我们就看到了下面这些方法:
withHolder(Function<Descriptor.DescriptorBuilder<T>, Descriptor<? extends T, H>> descriptorCreator)
参数的类型很长,有些复杂,从方法名来看,可以视为提问:需要显示哪些ViewHolder
?而参数是一个名为descriptorCreator
的Function
,这是一个将一个构造器转换为Descriptor
的过程,这个Descriptor
自然描述的是对应ViewHolder
的信息。
于是我们写下:
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> {// 返回什么呢 })
那么我们如何得到Descriptor
呢?
步骤3.1
输入builder
后再次按下.
,编辑器提示holderOf(Class<H> holderClass)
方法,意思是:你要为哪类ViewHolder
创建Descriptor
?这里需要提供一个ViewHolder
的class,比如:
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class))
步骤3.2
holderOf
的返回值不符合要求,我们再次输入.
,看到了下面两个方法:
createBy(Function<ViewGroup, H> function)
createByDefault()
意思就是:要如何创建该类型的ViewHolder
对象?createBy
需要提供一个从ViewGroup
创建ViewHolder
对象的过程;而createByDefault
根据默认方式创建(这需要对应ViewHolder提供单个ViewGroup参数的构造方法,且该ViewHolder
类不为非静态内部类)。因此,我们可以这样写
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createByDefault())
//或
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(VideoHolder::new))
//或
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)))
步骤3.3
返回值仍然不满足要求,继续.
,我们看到下面5个方法:
inWherePositionOf(int position)
和inWherePositionOf(Function<NeoListAdapter<T>, Integer> positionMapper)
,在指定position
的位置才可以显示inWhereTypeOf(Class<D> clazz)
:list中数据类型为clazz
的位置才可以显示inWhereSatisfy(Predicate<T> predicate)
:满足predicate
才可以显示inAllPlace()
:在所有位置都可以显示
这就是在问:在什么位置显示这个ViewHolder
?我可以这样写:
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereTypeOf(Video.class))
//或
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereSatisfy(media -> media instanceof Video))
步骤3.4
返回值仍然不满足要求,继续.
,我们看到一个方法:bindWith(BiConsumer<H, T> binder)
。对应提问:如何向这个数据绑定到该ViewHolder
上?其实就是对应Adapter的onBindViewHolder
方法。所以我们可以编写:
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereTypeOf(Video.class).bindWith((holder, media) -> holder.setData(media)))
//或
NeoListAdapter.dataFor(mediaList).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder((builder) -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereTypeOf(Video.class).bindWith(VideoHolder::bindData))
bindWith
的返回值符合要求,这样就结束了一个Descriptor
的创建。(这里假定VideoHolder
提供了setData
或bindData
方法用于将数据显示到该VideoHolder
)
步骤4
我们在withHolder
方法的调用后在输入.
,可以看到还能调用withHolder
,意思就是可以绑定多个类型的ViewHolder
。比如:
NeoListAdapter.dataFor(Media.class).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder(builder -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereTypeOf(Video.class).bindWith(VideoHolder::bindData)).withHolder(builder -> builder.holderOf(MusicHolder.class).createBy(MusicHolder::new).inWhereSatisfy(t -> t instanceof Music).bindWith(MusicHolder::bindData));
除此以外还有一个build
方法,返回NeoListAdapter
对象,也就是我们最终要的东西:
NeoListAdapter<Media> adapter = NeoListAdapter.dataFor(Media.class).diffBy(Objects::equals, (m1,m2) -> Objects.equals(m1.path, m2.path)).withHolder(builder -> builder.holderOf(VideoHolder.class).createBy(viewGroup -> new VideoHolder(viewGroup)).inWhereTypeOf(Video.class).bindWith(VideoHolder::bindData)).withHolder(builder -> builder.holderOf(MusicHolder.class).createBy(MusicHolder::new).inWhereSatisfy(t -> t instanceof Music).bindWith(MusicHolder::bindData)).build();
设计思路
其实这个类的灵感来自于新手机启动的帮助引导设置,比如一开始让你选择系统语言,然后连上wifi,再设置导航栏行为之类的。就是一步步引导用户设置,每一步都对应一类操作/设置,最终完成手机基本功能的设置。
这个类也是如此,想要简洁,使用一个建造者builder链式调用就可以,但是传统建造者会产生多个选项,并且可以反复/无序调用,所以我采用了多个建造者来构成建造者链,每一个建造者只有一类选项,进而达到“引导”的效果。
正因为是“引导”,所以不需要记忆,只要不断的输入.
就可以完成。也就是“让代码和编辑器提示”来告诉我怎么用。
NeoListAdapter 完整实现
import android.view.ViewGroup;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.*;public abstract class NeoListAdapter<T> extends ListAdapter<T, RecyclerView.ViewHolder> {private static final ThreadPoolExecutor sBackgroundExecutor = new ThreadPoolExecutor(0, Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200));private NeoListAdapter(@NonNull DiffUtil.ItemCallback<T> diffCallback) {super(new AsyncDifferConfig.Builder<>(diffCallback).setBackgroundThreadExecutor(sBackgroundExecutor).build());}public static <T> DifferBuilder<T> dataFrom(List<T> list) {return dataFrom(listConsumer -> listConsumer.accept(list));}public static <T> DifferBuilder<T> dataFrom(Consumer<Consumer<List<T>>> dataSupplierConsumer) {return new DifferBuilder<>(adapter -> dataSupplierConsumer.accept(list -> adapter.submitList(new ArrayList<>(list))));}public static <T> DifferBuilder<T> dataFor(Class<T> clazz) {return dataFrom(new ArrayList<>(0));}public static class DifferBuilder<T> {final Consumer<NeoListAdapter<T>> adapterConsumer;public DifferBuilder(Consumer<NeoListAdapter<T>> adapterConsumer) {this.adapterConsumer = adapterConsumer;}public HolderBuilder<T> contentDiffBy(BiPredicate<T, T> contentSamePredicate) {return diffBy(Objects::equals, contentSamePredicate);}public HolderBuilder<T> itemDiffBy(BiPredicate<T, T> itemSamePredicate) {return diffBy(itemSamePredicate, Objects::equals);}public HolderBuilder<T> diffByDefault() {return diffBy(Objects::equals, Objects::equals);}public HolderBuilder<T> diffBy(BiPredicate<T, T> itemSamePredicate, BiPredicate<T, T> contentSamePredicate) {return diffBy(new DiffUtil.ItemCallback<T>() {@Overridepublic boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem) {return itemSamePredicate.test(oldItem, newItem);}@Overridepublic boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem) {return contentSamePredicate.test(oldItem, newItem);}});}public HolderBuilder<T> diffBy(DiffUtil.ItemCallback<T> itemCallback) {return new HolderBuilder<>(adapterConsumer, itemCallback);}}public static class HolderBuilder<T> {final Consumer<NeoListAdapter<T>> adapterConsumer;final DiffUtil.ItemCallback<T> diffCallback;private final List<Descriptor> descriptors = new ArrayList<>();public HolderBuilder(Consumer<NeoListAdapter<T>> adapterConsumer, DiffUtil.ItemCallback<T> callback) {this.adapterConsumer = adapterConsumer;this.diffCallback = callback;}public <H extends RecyclerView.ViewHolder> HolderBuilder<T> withHolder(Function<Descriptor.DescriptorBuilder<T>, Descriptor<? extends T, H>> descriptorCreator) {descriptors.add(descriptorCreator.apply(new Descriptor.DescriptorBuilder<>()));return this;}public NeoListAdapter<T> build() {Map<Class<?>, BiConsumer<RecyclerView.ViewHolder, T>> binderMap = new HashMap<>();List<Function<Integer, Integer>> typeConditions = new LinkedList<>();Function<ViewGroup, RecyclerView.ViewHolder>[] creators = new Function[descriptors.size() + 1];return new NeoListAdapter<T>(diffCallback) {{for (int i = 0; i < descriptors.size(); i++) {Descriptor<T, RecyclerView.ViewHolder> descriptor = descriptors.get(i);descriptor.adapter = this;int itemViewType = i + 1;typeConditions.add(pos -> {if (descriptor.typePredicate.test(pos)) {return itemViewType;} else {return -1;}});creators[itemViewType] = descriptor.creator;binderMap.put(descriptor.holderClass, descriptor.binder);}}@Overridepublic void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {super.onAttachedToRecyclerView(recyclerView);adapterConsumer.accept(this);}@NonNull@Overridepublic RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {return creators[viewType].apply(parent);}@Overridepublic void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {Optional.ofNullable(binderMap.get(holder.getClass())).ifPresent(consumer -> consumer.accept(holder, getCurrentList().get(position)));}@Overridepublic int getItemViewType(int position) {for (Function<Integer, Integer> f : typeConditions) {Integer type = f.apply(position);if (type >= 0) {return type;}}throw new IllegalStateException("can not find a view type");}};}}public static final class Descriptor<T, H extends RecyclerView.ViewHolder> {BiConsumer<H, T> binder;Function<ViewGroup, H> creator;Predicate<Integer> typePredicate;final Class<H> holderClass;NeoListAdapter<T> adapter;private Descriptor(Class<H> holderClass) {this.holderClass = holderClass;}public static class DescriptorBuilder<T> {public <H extends RecyclerView.ViewHolder> Descriptor<T, H>.HolderCreatorBuilder holderOf(Class<H> holderClass){Descriptor<T, H> descriptor = new Descriptor<>(holderClass);return descriptor.new HolderCreatorBuilder();}}public class HolderCreatorBuilder {public TypePredicateBuilder createBy(Function<ViewGroup, H> function) {Descriptor.this.creator = function;return new TypePredicateBuilder();}public TypePredicateBuilder createByDefault() {try {Constructor<?> constructor = holderClass.getConstructor(ViewGroup.class);int modifiers = constructor.getModifiers();if (Modifier.isPublic(modifiers)) {Descriptor.this.creator = viewGroup -> {try {return (H) constructor.newInstance(viewGroup);} catch (IllegalAccessException | InstantiationException |InvocationTargetException e) {throw new RuntimeException(e);}};} else {throw new IllegalArgumentException(String.format("The class[%s]'s construct is not public", holderClass.getCanonicalName(), modifiers));}} catch (NoSuchMethodException e) {throw new IllegalArgumentException(String.format("The class[%s] don't contains constructor with a ViewGroup parameter", holderClass.getCanonicalName()), e);}return new TypePredicateBuilder();}}public class TypePredicateBuilder {public BinderBuilder inWherePositionOf(int position) {Descriptor.this.typePredicate = pos -> Objects.equals(pos, position);return new BinderBuilder();}public BinderBuilder inWherePositionOf(Function<NeoListAdapter<T>, Integer> positionMapper) {Descriptor.this.typePredicate = pos -> Objects.equals(pos, positionMapper.apply(adapter));return new BinderBuilder();}public <D extends T> Descriptor<D, H>.BinderBuilder inWhereTypeOf(Class<D> clazz) {Descriptor.this.typePredicate = pos -> clazz.isInstance(adapter.getCurrentList().get(pos));return (Descriptor<D, H>.BinderBuilder) new BinderBuilder();}public BinderBuilder inWhereSatisfy(Predicate<T> predicate) {Descriptor.this.typePredicate = pos -> predicate.test(adapter.getCurrentList().get(pos));return new BinderBuilder();}public BinderBuilder inAllPlace() {return inWhereSatisfy(t -> true);}}public class BinderBuilder {public Descriptor<T, H> bindWith(BiConsumer<H, T> binder) {Descriptor.this.binder = binder;return Descriptor.this;}}}
}