万能RecyclerView适配器

本文介绍了一个简化版RecyclerView Adapter的实现方法,通过自定义工具类来减少编写Adapter时的繁琐步骤,支持多种布局如header, footer及content等,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请声明:http://blog.youkuaiyun.com/yoyo_newbie/article/details/48827171

相信用RecyclerView的人都知道,写RecyclerView adapter比listview的apdater繁琐,还有不带onItemClickedlistener,要自己手工去添加。

如果只有一个布局Item好说,但是如果让你添加header, footer, content ,group共存的adapter,而且又给它们手工添加点击事件,是不是很烦?

由于这个困恼,所以实现了个简单好用的工具类,提供注入写法加速项目开发。

添加导入:

 compile 'com.github.sam474850601:samreclecerviewadapter:1.0.2'


项目下载github地址:https://github.com/Sam474850601/RecyclerViewAdapterDemo


定义一个item布局

adapter_layout_recyclerview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_data"
        android:text="111"
        />
</LinearLayout>




holder的写法

//注入item布局
@ConfigLayout(R.layout.adapter_layout_recyclerview)
private static  class ContentHolder implements  HolderSerialize
{
    //注入View的id ,让框架本身给它提供引用
    @ConfigView(R.id.tv_data)
    TextView dataView;
}



adapter写法

//泛型类别分别是内容,分组, 头部,尾部。部分不实现用Null代替
private class MyViewAdapter extends BaseRecyclerViewAdapter<ContentHolder,Null, Null, Null>
{
    public MyViewAdapter(Context context) {
        super(context);
    }

    //列表内容每一项的绘制
    @Override
    protected void onContentUpdate(ContentHolder holder, int position, Item item) {
        TextView dataView = holder.dataView;
        dataView.setText((String) item.data);
    }

    //列表的点击事件
    @Override
    public void onContentClicked(View view, int position, Item item) {
        Toast.makeText(getApplicationContext(), ""+item.data, Toast.LENGTH_SHORT).show();
    }
}



使用:


MyViewAdapter adapter = new MyViewAdapter(this);
recyclerView.setAdapter(adapter);
for(int i = 0; i < 10; i ++)
{
    ContentItem item = new ContentItem();
    item.data = ""+i;
    adapter.getItemList().add(item);
}
adapter.notifyDataSetChanged();

是不是代码很简洁就实现了这个apdater?6不6? 多个布局请到github下载








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值