Android--RecyclerView的封装使用

1,用了很长一段时间的RecyclerView,在项目中用的频率也越来越频繁(因为踩得坑也越来越多了),或过头来看,感觉一直在写RecyclerView.Adapter中的三个方法和一个内部类,感觉很浪费时间,那么今天我们来试着封装封装,来减少我们的使用

先看一下我们的实现效果:

2,我们来简单的写一写吧,首先我们按照以前的方式写的话,看看有哪些代码,我们先来发出来看看

UserSimpleRecyclerAdapter.java

package com.qianmo.myview2.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.qianmo.myview2.R;
import com.qianmo.myview2.bean.UserBean;

import org.w3c.dom.Text;

import java.util.List;

/**
 * Created by wangjitao on 2016/11/7 0007.
 */
public class UserSimpleRecycleAdapter extends RecyclerView.Adapter<UserSimpleRecycleAdapter.ViewHolder> {
    private Context context;
    private LayoutInflater inflater;
    private List<UserBean> datas;

    public UserSimpleRecycleAdapter(Context context, List<UserBean> datas) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.datas = datas;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.item_user, parent, false);
        ViewHolder holder = new ViewHolder(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.tv_name.setText(datas.get(position).getName());
        holder.tv_age.setText(datas.get(position).getAge());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv_name;
        TextView tv_age;

        public ViewHolder(View itemView) {
            super(itemView);

            tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            tv_age = (TextView) itemView.findViewById(R.id.tv_age);
        }
    }
}

  可以看到 getItemCount()、onCreateViewHolder()、onBindViewHolder()再加上ViewHolder内部类是我们必须要写的,但是写长了我们就可以感觉到  getItemCount()是基本上代码相同的,一般在onCreateViewHolder中创建ViewHolder,在onBindViewHolder中写数据和逻辑 ,而我们程序员最管关心什么呢  就是数据和逻辑的处理啊 ,如果我们创建一个适配器只用写我们的逻辑的话,那我们每天都可以省下好多时间来打一把lol了,现在带大家一步一步封装吧!

首先看一下我们最关键的BaseViewHolder

BaseViewHolder.java

package com.qianmo.myview2.base;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

/**
 * Created by wangjitao on 2016/11/7 0007.
 * 万能的Viewholder
 */
public class BaseViewHolder extends RecyclerView.ViewHolder {

    private SparseArray<View> views;

    public BaseViewHolder(View view) {
        super(view);
        this.views = new SparseArray<>();
    }

    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public View getRootView() {
        return itemView;
    }
}

 其实里面重要的就是views属性和getView()方法 ,getView方法中用户通过传递控件的id然后首先会去views这个集合中去拿,如果没有的话说明是我们的头部,这样就解决了多次findView的问题,好像里面也没什么难懂的,大家就看看吧。

  再看一下我们的抽象类BaseRecycleViewAdapter

 BaseRecycleViewAdapter.java

package com.qianmo.myview2.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.balysv.materialripple.MaterialRippleLayout;
import com.qianmo.myview2.R;

import java.util.List;

/**
 * Created by wangjitao on 2016/11/7 0007.
 * 对简单的recycleview进行简单的封装
 */
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private Context context;
    private LayoutInflater inflater;
    private List<T> datas;
    private int layoutId;
    protected OnItemClickListner onItemClickListner;//单击事件
    protected OnItemLongClickListner onItemLongClickListner;//长按单击事件
    private boolean clickFlag = true;//单击事件和长单击事件的屏蔽标识

    public BaseRecyclerViewAdapter(Context context, List<T> datas, int layoutId) {
        this.context = context;
        this.datas = datas;
        this.layoutId = layoutId;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder holder = new BaseViewHolder(inflater.inflate(layoutId, parent, false));
        MaterialRippleLayout.on(holder.getView(R.id.ll_all))
                .rippleOverlay(true)
                .rippleAlpha(0.2f)
                .rippleColor(context.getResources().getColor(R.color.colorAccent))
                .rippleHover(true)
                .create();
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        bindData(holder, datas.get(position), position);
    }

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

    protected abstract void bindData(BaseViewHolder holder, T data, int position);

    public void setOnItemClickListner(OnItemClickListner onItemClickListner) {
        this.onItemClickListner = onItemClickListner;
    }

    public void setOnItemLongClickListner(OnItemLongClickListner onItemLongClickListner) {
        this.onItemLongClickListner = onItemLongClickListner;
    }

    public interface OnItemClickListner {
        void onItemClickListner(View v, int position);
    }

    public interface OnItemLongClickListner {
        void onItemLongClickListner(View v, int position);
    }
}

 我们在里面处理了onCreateViewHolder和getItemCount这两个我们一直写的方法,通过抽象方法把我们最重要的onBindViewHolder方法暴露出去,这样我们就可以在暴露出去的bindData()方法中去处理逻辑了,并且添加了创建的Item点击事件和长按事件。

 我们写一个简单的用户展示列表看看效果如何,创建UserAdapter.java,看一下代码:

 

package com.qianmo.myview2.base;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qianmo.myview2.R;
import com.qianmo.myview2.bean.UserBean;

import java.util.List;

/**
 * Created by Administrator on 2016/11/7 0007.
 */
public class UserAdapter extends BaseRecyclerViewAdapter<UserBean> {


    public UserAdapter(Context context, List<UserBean> datas, int layoutId) {
        super(context, datas, layoutId);
    }

    @Override
    protected void bindData(final BaseViewHolder holder, UserBean data, final int position) {
        LinearLayout ll_all = (LinearLayout) holder.getView(R.id.ll_all);
        TextView tv_name = (TextView) holder.getView(R.id.tv_name);
        TextView tv_age = (TextView) holder.getView(R.id.tv_age);

        tv_age.setText(data.getAge());
        tv_name.setText(data.getName());

        ll_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onItemClickListner != null) {
                    onItemClickListner.onItemClickListner(holder.getRootView(), position);
                }
            }
        });
    }
}

  就问一句爽不爽 ,只需要写一个方法了,还有谁!

再把完整的代码贴出来一下

UserBean.java

package com.qianmo.myview2.bean;

/**
 * Created by Administrator on 2016/11/7 0007.
 */
public class UserBean {
    public UserBean(String name, String age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

 item_user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="#ffffff"
              android:orientation="vertical"
    >

    <LinearLayout
        android:id="@+id/ll_all"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#ffffff"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            >

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="王继涛"
                android:textColor="#000000"
                android:textSize="16sp"
                />

            <TextView
                android:id="@+id/tv_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="30dp"
                android:text="18381339409"
                android:textColor="#000000"
                android:textSize="16sp"
                />
        </LinearLayout>


    </LinearLayout>
</LinearLayout>

  MainActivity.java

package com.qianmo.myview2;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.qianmo.myview2.base.BaseRecyclerViewAdapter;
import com.qianmo.myview2.base.UserAdapter;
import com.qianmo.myview2.base.UserSimpleRecycleAdapter;
import com.qianmo.myview2.bean.UserBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements BaseRecyclerViewAdapter.OnItemClickListner {


    private RecyclerView recycleView;

    private Context mContext = MainActivity.this;
    private UserAdapter mAdapter;
    private UserSimpleRecycleAdapter mUserSimpleRecycleAdapter;
    private List<UserBean> datas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recycleView = (RecyclerView) findViewById(R.id.recycleView);

        initView();
    }

    private void initData() {
        datas = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            datas.add(new UserBean("wangjtiao", "" + i));
        }
    }

    private void initView() {
        initData();
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLinearLayoutManager);

        mAdapter = new UserAdapter(mContext, datas, R.layout.item_user);
        mAdapter.setOnItemClickListner(this);

//        mUserSimpleRecycleAdapter = new UserSimpleRecycleAdapter(mContext, datas);
        recycleView.setAdapter(mAdapter);

    }

    @Override
    public void onItemClickListner(View v, int position) {
        Toast.makeText(mContext, datas.get(position).getName() + ":" + datas.get(position).getAge() + ":" + position, Toast.LENGTH_SHORT).show();
    }
}

  ok,这样我们就封装完了·······

 

 

posted @ 2016-11-07 18:02  阿呆哥哥  阅读(4961)  评论(2编辑  收藏  举报