RecyclerView简单使用

偶尔善良 提交于 2019-12-02 12:41:31
package com.example.recyclerviewtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class RecyclerViewActivity extends AppCompatActivity implements View.OnClickListener {

    RecyclerView recyclerView;
    Button btn_add;
    Button btn_del;
    Button btn_list;
    Button btn_grid;
    Button btn_flow;
    List<String> datas;
    private MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        initViews();

        initdatas();

        //设置adapter
        adapter = new MyRecyclerViewAdapter(RecyclerViewActivity.this, datas);
        recyclerView.setAdapter(adapter);

        //设置分割线
        recyclerView.addItemDecoration(new DividerListItemDecoration(RecyclerViewActivity.this, DividerListItemDecoration.HORIZONTAL_LIST));
        recyclerView.addItemDecoration(new DividerListItemDecoration(RecyclerViewActivity.this, DividerListItemDecoration.VERTICAL_LIST));


        adapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnItemclickListner() {
            @Override
            public void OnItemClick(View view, String data) {
                Toast.makeText(RecyclerViewActivity.this, "data = " + data, Toast.LENGTH_SHORT).show();

            }
        });


        //设置动画s
        recyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    private void initdatas() {
        datas = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            datas.add("content_" + i);
        }
    }

    @SuppressLint("WrongConstant")
    private void initViews() {
        btn_add = findViewById(R.id.btn_add);
        btn_del = findViewById(R.id.btn_del);
        btn_list = findViewById(R.id.btn_list);
        btn_grid = findViewById(R.id.btn_grid);
        btn_flow = findViewById(R.id.btn_flow);
        btn_add.setOnClickListener(this);
        btn_del.setOnClickListener(this);
        btn_list.setOnClickListener(this);
        btn_grid.setOnClickListener(this);
        btn_flow.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewActivity.this, LinearLayoutManager.VERTICAL, false));

    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_add:
                adapter.addData(0, "zhangsan");
                recyclerView.scrollToPosition(0);
                break;
            case R.id.btn_del:
                adapter.removeData(0);
                break;
            case R.id.btn_list:
                //设置LayoutManager
                //最后一位代表时顺序还是倒序
                recyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewActivity.this, LinearLayoutManager.VERTICAL, false));
                //recyclerView.scrollToPosition(datas.size()/2);//定位到中间位置
                break;
            case R.id.btn_grid:
                //设置成3列
                //最后一位代表时顺序还是倒序
                recyclerView.setLayoutManager(new GridLayoutManager(RecyclerViewActivity.this, 3, GridLayoutManager.VERTICAL, false));
                break;
            case R.id.btn_flow:
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
                break;
        }

    }
}

定义Adapter

package com.example.recyclerviewtest;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {

    private Context context;
    private List<String> datas;

    public MyRecyclerViewAdapter(Context context, List<String> datas) {
        this.context = context;
        this.datas = datas;
    }

    /**
     * 相当于getView方法中船舰view和viewHodler
     *
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = View.inflate(context, R.layout.item_layout, null);
        return new MyViewHolder(itemView);
    }

    /**
     * 相当于getview绑定数据的部分
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        //根据位置得到的数据
        String data = datas.get(position);
        holder.tv_text.setText(data);
    }

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

    private OnItemclickListner ItemClickListener;

    public void setOnItemClickListener(OnItemclickListner itemClickListener) {
        this.ItemClickListener = itemClickListener;
    }

    public void addData(int position, String data) {
        datas.add(position, data);
        notifyItemInserted(position);
    }

    public void removeData(int i) {
        if (datas.size() > 0) {
            datas.remove(i);
            notifyItemRemoved(i);
        }
    }

    public interface OnItemclickListner {
        void OnItemClick(View view, String data);
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView iv_icon;
        private TextView tv_text;

        public MyViewHolder(@NonNull final View itemView) {
            super(itemView);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_text = itemView.findViewById(R.id.tv_text);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ItemClickListener != null) {
                        ItemClickListener.OnItemClick(itemView, datas.get(getLayoutPosition()));
                    }
                }
            });
        }
    }
}

设置分隔符 DividerListItemDecoration

package com.example.recyclerviewtest;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class DividerListItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerListItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.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) {
//        Log.e("recyclerview - itemdecoration", "onDraw()");

        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }

    }


    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

设置分割线xml文件

首先定义个drawable

divider_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />

    <size android:height="2dp" />
</shape>

设置style

    <style name="listDividerTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:listDivider">@drawable/divider_bg</item>
    </style>
AndroidManifest.xml中设置Activity的分割<activity    android:name=".RecyclerViewActivity"    android:theme="@style/listDividerTheme"></activity>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!