Recyclerviewdemo

来源:互联网 发布:淘宝代充为什么便宜 编辑:程序博客网 时间:2024/06/08 11:34
依赖:
compile 'com.android.support:recyclerview-v7:25.3.1'
主界面:
public class MainActivity extends AppCompatActivity {    private RecyclerView recyclerView;    private LinearLayoutManager linearLayoutManager;    private GridLayoutManager gridLayoutManager;    private StaggeredGridLayoutManager staggeredGridLayoutManager;    private MyAdapter adapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        recyclerView = (RecyclerView) findViewById(R.id.recycler);        //线性布局        linearLayoutManager = new LinearLayoutManager(this);        //网格布局        gridLayoutManager = new GridLayoutManager(this,3);        //通过setSpanSizeLookup 来自定义每个item占的列数        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {            @Override            public int getSpanSize(int position) {                return 3-position%3;            }        });        //瀑布流布局        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);        //为recyclerView设置布局样式        recyclerView.setLayoutManager(linearLayoutManager);        adapter = new MyAdapter();        recyclerView.setAdapter(adapter);        adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {            @Override            public void onItemClick(View v, int position) {               // adapter.add(position);               //在这里设置item的点击事件,可以增加,删除,修改,也可以添加复选框进行反选。。              adapter.quanxuan();            }        });        adapter.setOnItemLongClickListener(new MyAdapter.OnItemLongClickListener() {            @Override            public void onItemLongClick(View v, int position) {                //adapter.remove(position);                adapter.update(position,"这是我更新的内容");            }        });        recyclerView.addItemDecoration(new MyDecoration(this,LinearLayoutManager.VERTICAL));    }    public void Button(View view){        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();        if(layoutManager == null){            return;        }        if(layoutManager instanceof GridLayoutManager){            recyclerView.setLayoutManager(linearLayoutManager);            //重新设置adapter之后 ,会重新走oncreateViewholder可以改变我们的布局            recyclerView.setAdapter(adapter);        }else if(layoutManager instanceof LinearLayoutManager){            recyclerView.setLayoutManager(gridLayoutManager);            //重新设置adapter之后 ,会重新走oncreateViewholder可以改变我们的布局            recyclerView.setAdapter(adapter);        }    }}
MyAdapter适配器类:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {    ArrayList<String> list;    HashMap<Integer, Boolean> isCheckedHashMap;    public MyAdapter() {        list = new ArrayList<>();        isCheckedHashMap = new HashMap<>();创建一个集合        for (int i = 0; i < 30; i++) {            list.add("条目" + i);添加数据            isCheckedHashMap.put(i,false);        }    }    //创建布局和viewHolder    @Override    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        RecyclerView.LayoutManager layoutManager = ((RecyclerView) parent).getLayoutManager();        View recyclerViewItem = null;        if(layoutManager instanceof GridLayoutManager){            //inflate的时候,需要传入parent和attachToRoot==false; 使用传入三个参数的方法            recyclerViewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);        }else if(layoutManager instanceof LinearLayoutManager){            //inflate的时候,需要传入parent和attachToRoot==false; 使用传入三个参数的方法            recyclerViewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item2,parent,false);        }        return new MyViewHolder(recyclerViewItem);    }    public void add(int position) {        list.add(position + 1, "这是新加的");        notifyItemRangeChanged(position + 1, getItemCount());    }    public void remove(int position) {        list.remove(position);        notifyItemRangeChanged(position, getItemCount()        );    }    public void update(int position, String content) {        list.remove(position);        list.add(position, content);        notifyItemChanged(position);    }    public void quanxuan(){        Set<Map.Entry<Integer, Boolean>> entries = isCheckedHashMap.entrySet();        boolean shouldSelectedAll = false;        for (Map.Entry<Integer, Boolean> entry : entries) {            Boolean value = entry.getValue();            //如果有没选中的,那就去全部选中 ,如果发现全都选中了那就全部不选中,            if (!value) {                shouldSelectedAll = true;                break;            }        }        for (Map.Entry<Integer, Boolean> entry : entries) {            entry.setValue(shouldSelectedAll);        }        notifyDataSetChanged();     }   
public void fanxun() {     Set<Map.Entry<Integer, Boolean>> entries = ischeckHashMap.entrySet();     for (Map.Entry<Integer, Boolean> entry : entries) {         entry.setValue(!entry.getValue());     }     notifyDataSetChanged(); } public void danxun(int position) {     Set<Map.Entry<Integer, Boolean>> entries = ischeckHashMap.entrySet();     for (Map.Entry<Integer, Boolean> entry : entries) {         entry.setValue(false);     }     ischeckHashMap.put(position, true);     notifyDataSetChanged(); }

 public interface OnItemClickListener { void onItemClick(View v, int position); } public interface OnItemLongClickListener { void onItemLongClick(View v, int position); } private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener mOnItemLongClickListener; public void setOnItemClickListener(OnItemClickListener itemClickListener) { mOnItemClickListener = itemClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener itemlongClickListener) { mOnItemLongClickListener = itemlongClickListener; } //绑定数据 @Override public void onBindViewHolder(MyViewHolder holder, final int position) { holder.wenzi.setText(list.get(position)); if (position % 2 == 1) { holder.img.setImageResource(R.mipmap.ic_launcher); } holder.img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //暴露一个单击回调接口  if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(v, position); } } }); holder.img.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnItemLongClickListener != null) { mOnItemLongClickListener.onItemLongClick(v, position); } return true; } }); holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isCheckedHashMap.put(position,!isCheckedHashMap.get(position)); notifyDataSetChanged(); } }); holder.checkBox.setChecked(isCheckedHashMap.get(position)); } @Override public int getItemCount() { return list.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView wenzi; ImageView img; CheckBox checkBox; View itemView; public MyViewHolder(View itemView) { super(itemView); this.itemView = itemView; wenzi = (TextView) itemView.findViewById(R.id.wenzi); img = (ImageView) itemView.findViewById(R.id.img); checkBox = (CheckBox) itemView.findViewById(R.id.box); } }}
MyDecoration类:
public class MyDecoration extends RecyclerView.ItemDecoration {    private Context mContext;    private Drawable mDivider;    private int mOrientation;    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;    //我们通过获取系统属性中的listDivider来添加,在系统中的AppTheme中设置    public static final int[] ATRRS = new int[]{            android.R.attr.listDivider    };    public MyDecoration(Context context, int orientation) {        this.mContext = context;        final TypedArray ta = context.obtainStyledAttributes(ATRRS);        this.mDivider = ta.getDrawable(0);        ta.recycle();        setOrientation(orientation);    }    //设置屏幕的方向    public void setOrientation(int orientation) {        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {            throw new IllegalArgumentException("invalid orientation");        }        mOrientation = orientation;    }    @Override    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {        if (mOrientation == HORIZONTAL_LIST) {            drawVerticalLine(c, parent, state);        } else {            drawHorizontalLine(c, parent, state);        }    }    //画横线, 这里的parent其实是显示在屏幕显示的这部分    public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {        int left = parent.getPaddingLeft();        int right = parent.getWidth() - parent.getPaddingRight();        final int childCount = parent.getChildCount();        for (int i = 0; i < childCount; i++) {            final View child = parent.getChildAt(i);            //获得child的布局信息            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();            final int top = child.getBottom() + params.bottomMargin;            final int bottom = top + mDivider.getIntrinsicHeight();            mDivider.setBounds(left+params.leftMargin, top, right-params.leftMargin, bottom);            mDivider.draw(c);            //Log.d("wnw", left + " " + top + " "+right+"   "+bottom+" "+i);        }    }    //画竖线    public void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {        int top = parent.getPaddingTop();        int bottom = parent.getHeight() - parent.getPaddingBottom();        final int childCount = parent.getChildCount();        for (int i = 0; i < childCount; i++) {            final View child = parent.getChildAt(i);            //获得child的布局信息            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();            final int left = child.getRight() + params.rightMargin;            final int right = left + mDivider.getIntrinsicWidth();            mDivider.setBounds(left, top+params.topMargin, right, bottom-params.topMargin);            mDivider.draw(c);        }    }    //由于Divider也有长宽高,每一个Item需要向下或者向右偏移    @Override    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {        if (mOrientation == HORIZONTAL_LIST) {            //画横线,就是往下偏移一个分割线的高度            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());        } else {            //画竖线,就是往右偏移一个分割线的宽度            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);        }    }}//画横线
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <solid android:color="#ff0000" />    <size        android:height="2dp"        android:width="2dp"        /></shape>
主界面布局:
<android.support.v7.widget.RecyclerView    android:id="@+id/recycler"    android:layout_width="match_parent"    android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

原创粉丝点击