BaseRecyclerViewAdapterHelper使用记录(一)

2019-08-26 10:18:13 浏览数 (1)

添加依赖

代码语言:javascript复制
dependencies {
    ...
    implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:v2.1.1'
    ...
}
代码语言:javascript复制
allprojects {
    repositories {
    ...
        maven { url "https://jitpack.io" }
        google()
        jcenter()
        
    }
}

MultipleItem

BRVAH实现Adapter的代码量确实很少,减少原代码量70%左右,RecyclerView复杂布局必须实现的getItemType()方法竟然也不在Adapter中,所以出现了下面继承自MultiItemEntity的实体类MultipleItem和他的getItemType()方法,当然你也可以在这儿实现SpanSize跨度,代码:

代码语言:javascript复制
public class MultipleItem implements MultiItemEntity {
    public static final int ONE = 1;
    public static final int TWO = 2;
    public static final int IMG_TEXT = 3;
    private int itemType;

    public MultipleItem(int itemType) {
        this.itemType = itemType;
    }

    @Override
    public int getItemType() {
        return itemType;
    }
}

MultipleItemQuickAdapter

可以看到下面的代码很少,Adapter的臃肿会影响后期维护,也会影响心情想让你去吃顿火锅,对,这个很重要。在方法中我们用switch-case判断一下就好,代码:

代码语言:javascript复制
public class MultipleItemQuickAdapter extends BaseMultiItemQuickAdapter<MultipleItem> {

    MultipleItemQuickAdapter(List<MultipleItem> data) {
        super(data);
        addItemType(MultipleItem.ONE, R.layout.view_one);
        addItemType(MultipleItem.TWO, R.layout.view_two);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, MultipleItem item) {

        switch (helper.getItemViewType()) {
            case MultipleItem.ONE:
                //...
                break;
            case MultipleItem.TWO:
                //...
                break;
        }
    }

}

MainActivity

ViewType就是在这儿填进去的,这里for循环模拟ItemType,BRVAH自带五种动画,这个很爽

代码语言:java复制
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        List<MultipleItem> list = new ArrayList<>();
        
        for (int i = 0; i < 100; i  ) {
            list.add(new MultipleItem(MultipleItem.ONE));
            list.add(new MultipleItem(MultipleItem.TWO));
            }
            
        final MultipleItemQuickAdapter multipleItemAdapter = new MultipleItemQuickAdapter(list);
        // final GridLayoutManager manager = new GridLayoutManager(this, 1);
        
        multipleItemAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);//BRVAH自带动画超爽
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(multipleItemAdapter);
    }
}

看看效果

0 人点赞