recycleview使用

来源:互联网 发布:帝国cms视频管理系统 编辑:程序博客网 时间:2024/06/05 14:07

简介

RecyclerView的官方资料介绍是:A flexible view for providing a limited window into a large data set,大体意思就是RecyclerView是一个用于显示大量数据的弹性视图控件。在RecyclerView出现之前,我们往往使用ListView显示大量的数据,对于ListView,其官方介绍是:A view that shows items in a vertically scrolling list,即垂直显示一组数据,注意这里加入了垂直两个字,这也正是RecyclerView和ListView的一个非常直观的区别。使用RecylclerView能够很容易的实现水平、垂直、瀑布流等显示样式,而ListView只能进行垂直显示。究其原因在于,ListView把布局方式硬编码进ListView类中,而RecyclerView则把布局方式和自身解耦。

我呢就直接做一个RecyclerView的使用

package com.example.recycleview;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;


import com.example.recycleview.Adapter.MyRecycleAdapter;
import com.example.recycleview.Bean.ItemBean;


import java.util.ArrayList;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private RecyclerView mRcCerylist;
    /**
     * 单列
     */
    private Button mBtDl;
    /**
     * 网格
     */
    private Button mBtWg;
    /**
     * 瀑布
     */
    private Button mBtPb;
    /**
     * 删除
     */
    private Button mBtDelete;
    /**
     * 添加
     */
    private Button mBtAdd;
    private ArrayList<ItemBean> list;
    private MyRecycleAdapter adapter;
    private SwipeRefreshLayout mSrl;
    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //刷新新的数据,并且清空里面的数据
                    mSrl.setRefreshing(false);
                    list.clear();
                    for (int i = 0; i < 10; i++) {
                        ItemBean itemBean = new ItemBean("更新完之后的name:" + i + ",新的价格:", i, false);
                        list.add(itemBean);
                    }
                    adapter = new MyRecycleAdapter(MainActivity.this, list);
                    mRcCerylist.setAdapter(adapter);
                    adapteronclick();
                    break;
            }
        }
    };
    /**
     * 全选
     */
    private CheckBox mCbMainCheckedall;
    /**
     * 反选
     */
    private CheckBox mCbMainRevese;
    /**   */
    private TextView mTvPrice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mBtDl.setBackgroundColor(Color.BLUE);
        mRcCerylist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        addinfo();
        adapteronclick();
        refresh();


    }


    //得到id
    private void initView() {
        mRcCerylist = (RecyclerView) findViewById(R.id.rc_cerylist);
        mBtDl = (Button) findViewById(R.id.bt_dl);
        mBtWg = (Button) findViewById(R.id.bt_wg);
        mBtPb = (Button) findViewById(R.id.bt_pb);
        mBtDl.setOnClickListener(this);
        mBtWg.setOnClickListener(this);
        mBtPb.setOnClickListener(this);
        mBtDelete = (Button) findViewById(R.id.bt_delete);
        mBtDelete.setOnClickListener(this);
        mBtAdd = (Button) findViewById(R.id.bt_add);
        mBtAdd.setOnClickListener(this);
        mSrl = (SwipeRefreshLayout) findViewById(R.id.srl);
        mCbMainCheckedall = (CheckBox) findViewById(R.id.cb_main_checkedall);
        mCbMainCheckedall.setOnClickListener(this);
        mCbMainRevese = (CheckBox) findViewById(R.id.cb_main_revese);
        mCbMainRevese.setOnClickListener(this);
        mTvPrice = (TextView) findViewById(R.id.tv_price);
    }


    //从Adapter中传过来的监听
    private void adapteronclick() {
        adapter.setOnItemListener(new MyRecycleAdapter.OnItemListener() {
            @Override
            public void onitemclick(int position) {
                Toast.makeText(MainActivity.this, "点击---" + position, Toast.LENGTH_SHORT).show();
            }


            @Override
            public void AllSelect(boolean result) {
                mCbMainCheckedall.setChecked(result);
            }


            @Override
            public void ChangePrice(int price) {
                mTvPrice.setText(price + "");
            }


            @Override
            public void changerecese(boolean result) {
                mCbMainRevese.setChecked(result);
                setPrice();
            }


            @Override
            public void onitemLongclick(int position) {
                Toast.makeText(MainActivity.this, "长按---" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }


    //得到计算后的总价格丙炔赋值给mTvPrice
    private void setPrice() {
        int changeprice = adapter.changeprice();
        mTvPrice.setText(changeprice + "");
    }


    //设置初始值
    private void addinfo() {
        mRcCerylist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ItemBean itemBean = new ItemBean("name:" + i + "价格:", i, false);
            list.add(itemBean);
        }
        adapter = new MyRecycleAdapter(this, list);
        mRcCerylist.setAdapter(adapter);
    }


    //下拉刷新,三秒后运行
    private void refresh() {
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hander.sendEmptyMessageDelayed(0, 3000);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_dl:
                mRcCerylist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                clickchange(mBtDl, mBtWg, mBtPb);
                break;
            case R.id.bt_wg:
                mRcCerylist.setLayoutManager(new GridLayoutManager(this, 2));
                clickchange(mBtWg, mBtDl, mBtPb);
                break;
            case R.id.bt_pb:
                mRcCerylist.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
                clickchange(mBtPb, mBtDl, mBtWg);
                break;
            case R.id.bt_delete:
                adapter.changefo(false);
                break;
            case R.id.bt_add:
                adapter.changefo(true);
                break;
            case R.id.cb_main_checkedall:
                adapter.selecrAll(mCbMainCheckedall.isChecked());
                mCbMainRevese.setChecked(false);
                setPrice();
                break;
            case R.id.cb_main_revese:
                adapter.receseAll();
                setPrice();
                break;
        }
    }


    //三个按钮,点击的变为蓝色,其他的变为白色
    private void clickchange(Button dl, Button wg, Button pb) {
        dl.setBackgroundColor(Color.BLUE);
        wg.setBackgroundColor(Color.WHITE);
        pb.setBackgroundColor(Color.WHITE);
    }
}

//adapter的页面

package com.example.recycleview.Adapter;


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.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.example.recycleview.Bean.ItemBean;
import com.example.recycleview.R;


import java.util.ArrayList;



public class MyRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private ArrayList<ItemBean> list;
    private OnItemListener onItemListener;
    private ArrayList<Boolean> booleenlist;


    //定义的一个interface方法,传送给MainAcitivity,监听
    public interface OnItemListener {
        public void onitemclick(int position);


        public void AllSelect(boolean result);


        public void ChangePrice(int price);


        public void changerecese(boolean result);


        public void onitemLongclick(int position);
    }


    public void setOnItemListener(OnItemListener onItemListener) {
        this.onItemListener = onItemListener;
    }


    public MyRecycleAdapter(Context context, ArrayList<ItemBean> list) {
        this.context = context;
        this.list = list;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //加载写好的布局  调用viewholdertype
        View view = LayoutInflater.from(context).inflate(R.layout.item1, parent, false);
        ViewHolderType viewHolderType = new ViewHolderType(view);
        return viewHolderType;
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        //给布局里的参数设置值
        final ItemBean itemBean = list.get(position);
        final ViewHolderType viewHolderType = (ViewHolderType) holder;
        viewHolderType.tvName.setText(itemBean.getName());
        viewHolderType.tvAge.setText(itemBean.getAge() + "");
        setAllItemClick(position, viewHolderType);
        viewHolderType.rb_checked.setChecked(itemBean.isMycheched());
        //复选框设置一个点击事件interface传送过去
        viewHolderType.rb_checked.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断点击后,影响反选,反选设为false
                onItemListener.changerecese(false);
                //得到点击后的状态,传给itemBean
                boolean checked = viewHolderType.rb_checked.isChecked();
                itemBean.setMycheched(checked);
                //每次点击事件都计算里面的价格,然后通过interface监听
                int changeprice = changeprice();
                onItemListener.ChangePrice(changeprice);
                //当点击时候是选中状态,调用isAllSelected()方法循环判断这时候是否所有的都为选中状态
                if (checked) {
                    if (isAllSelected()) {
                        //所有选中状态直接调用selecrAll()方法吧所有的设值为true
                        selecrAll(checked);
                    }
                }
                //选中不选中都把参数传送过去,监听全选框为true或者false
                onItemListener.AllSelect(isAllSelected());
                notifyDataSetChanged();
            }
        });


    }


    //点击事件和长按事件
    private void setAllItemClick(final int position, ViewHolderType viewHolderType) {
        viewHolderType.ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemListener != null) {
                    onItemListener.onitemclick(position);
                }
            }
        });
        viewHolderType.ll.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemListener != null) {
                    onItemListener.onitemLongclick(position);
                }
                return true;
            }
        });
    }


    @Override
    public int getItemCount() {
        return list.size();
    }


    private class ViewHolderType extends RecyclerView.ViewHolder {
        //list的adapter中的viewholder优化
        private TextView tvName;
        private TextView tvAge;
        private LinearLayout ll;
        private CheckBox rb_checked;


        //得到所有的id
        public ViewHolderType(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            tvAge = itemView.findViewById(R.id.tv_age);
            ll = itemView.findViewById(R.id.ll);
            rb_checked = itemView.findViewById(R.id.rb_checked);
        }
    }


    //当点击选中一个时候,判断全部是否都选中
    private boolean isAllSelected() {
        for (int i = 0; i < list.size(); i++) {
            ItemBean Bean = list.get(i);
            if (!Bean.isMycheched()) {
                //没有全选
                return false;
            }
        }
        return true;
    }


    //直接点击全选复选框时候,判断状态并且传值
    public void selecrAll(boolean result) {
        for (int i = 0; i < list.size(); i++) {
            ItemBean Bean = list.get(i);
            Bean.setMycheched(result);
        }
        notifyDataSetChanged();
    }


    //添加和删除数据
    public void changefo(boolean result) {
        if (result) {
            ItemBean itemBean = new ItemBean("添加的name:" + 110 + "添加后的age:", +112, false);
            list.add(itemBean);
        } else {
            list.remove(0);
        }
        notifyDataSetChanged();
    }


    //选中的不选中,不选中的选中,反选
    public void receseAll() {
        booleenlist = new ArrayList<>();
        booleenlist.clear();
        boolean result = true;
        for (int i = 0; i < list.size(); i++) {
            ItemBean Bean = list.get(i);
            if (Bean.isMycheched()) {
                result = false;
            }
            Bean.setMycheched(!Bean.isMycheched());
            booleenlist.add(!Bean.isMycheched());
        }
        onItemListener.AllSelect(result);
        notifyDataSetChanged();
    }


    //计算价格,拥有点击事件和监听的都会调用到
    public int changeprice() {
        int price = 0;
        for (int i = 0; i < list.size(); i++) {
            ItemBean Bean = list.get(i);
            if (Bean.isMycheched()) {
                int age = Bean.getAge();
                price += age;
            }
        }
        return price;
    }
}

//Activity_main页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.recycleview.MainActivity">


    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal">


        <Button
            android:id="@+id/bt_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除" />


        <Button
            android:id="@+id/bt_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加" />


        <Button
            android:id="@+id/bt_dl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="单列" />


        <Button
            android:id="@+id/bt_wg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:text="网格" />


        <Button
            android:id="@+id/bt_pb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="瀑布" />
    </RadioGroup>
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal">


        <CheckBox
            android:id="@+id/cb_main_checkedall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选" />


        <CheckBox
            android:layout_marginRight="10dp"
            android:id="@+id/cb_main_revese"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="反选" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="总计:" />
        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" 元" />


    </RadioGroup>


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/srl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <android.support.v7.widget.RecyclerView
            android:id="@+id/rc_cerylist"
            android:layout_width="match_parent"
            android:layout_height="match_parent">


        </android.support.v7.widget.RecyclerView>
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

//item页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="#330000ff"
    android:gravity="center_vertical"
    android:orientation="horizontal">


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">


        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textSize="20sp" />


        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textSize="20sp" />
    </LinearLayout>


    <CheckBox
        android:id="@+id/rb_checked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />




</LinearLayout>