Using RecyclerView, Grid and waterfall flow are simple to implement

Table of contents

1. The use of RecyclerView

        1. Configure build.gradle

        2. Use RecyclerView

Second, the implementation of Grid

3. Realization of Waterfall

 1. Define the split distance in item_recycler as 2dp

2. Modify the adapter HomeAdapter code:

1. The use of RecyclerView

The effect is as follows:

 

        1. Configure build.gradle

As a result of the update of the dependent library, AndroidX completely replaces the support library, not only providing the same functionality, but also providing a new library. That is to say, the support-v7 library has been replaced. The specific configuration code is as follows:

    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'

        2. Use RecyclerView

The code is explained in the comments (if you don’t understand, you can send a private message), directly upload the code:

RecycleTestActivity:

public class RecycleTestActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private HomeAdapter myHomeAdapter;
    private List<String> mList = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_test);
        InitView();
        useRecycleView();//使用RecyclerView
        setListener();//设置监听事件
    }

    //初始化控件
    private void InitView() {
        recyclerView = (RecyclerView) this.findViewById(R.id.id_recyclerview);
        for (int i = 0; i < 20; i++) {
            mList.add(i + "");
        }
    }

    //使用RecyclerView布局管理
    public void useRecycleView(){
        //设置布局管理器
        /**
         * new LinearLayoutManager(this)指的是默认布局是水平布局
         * 如果要用垂直布局的话:
         *         LinearLayoutManager layoutManager = new LinearLayoutManager(this);
         *         layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
         *         recyclerView.setLayoutManager(layoutManager);
         */
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置item的添加和删除的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        myHomeAdapter = new HomeAdapter(mList, this);
        //设置显示分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(RecycleTestActivity.this,DividerItemDecoration.VERTICAL_LIST));


        recyclerView.setAdapter(myHomeAdapter);
    }

    public void setListener(){
        myHomeAdapter.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(RecycleTestActivity.this,
                        "点击第" + (position + 1) + "条",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, final int position) {
                new AlertDialog.Builder(RecycleTestActivity.this)
                        .setTitle("确定删除吗?")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                myHomeAdapter.removeData(position);
                            }
                        })
                        .show();
            }
        });
    }

}
DividerItemDecoration (divider line):
/**
 *  显示分割线
 */

public class DividerItemDecoration 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 DividerItemDecoration(Context context,int orientation){
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }
    public DividerItemDecoration(Context context){
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    private void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST){
            try {
                throw new IllegalAccessException("invalid orientation");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(@NonNull @NotNull Canvas c, @NonNull @NotNull RecyclerView parent, @NonNull @NotNull RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST){
            drawVertical(c,parent);
        }else {
            drawHorizontal(c,parent);
        }
    }


    private 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);
        }
    }


    private 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(@NonNull @NotNull Rect outRect, @NonNull @NotNull View view, @NonNull @NotNull RecyclerView parent, @NonNull @NotNull RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST){
            outRect.set(0,0,0,mDivider.getIntrinsicHeight());
        }else {
            outRect.set(0,0,mDivider.getIntrinsicWidth(),0);
        }
    }
}
HomeAdapter (adapter):
/**
 * 适配器
 */

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

    private List<String> mList;
    private Context mContext;
    private OnItemClickListener mOnItemClickListener;
    List<Integer> mHeight;





    public HomeAdapter(List<String> mList, Context mContext) {
        this.mList = mList;
        this.mContext = mContext;
        mHeight = new ArrayList<Integer>();
        for (int i = 0; i < mList.size(); i++) {
            mHeight.add((int)(100 + Math.random() * 300));
        }
    }

    public void removeData(int position){
        mList.remove(position);
        notifyItemRemoved(position);
    }



    @NonNull
    @NotNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        MyViewHolder holder =
                new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_recycler,parent,false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull HomeAdapter.MyViewHolder holder, int position) {
        holder.tv.setText(mList.get(position));
        if (mOnItemClickListener != null){
            holder.tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.tv,pos);
                }
            });

            holder.tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemLongClick(holder.tv,pos);
                    return false;
                }
            });
        }

        ViewGroup.LayoutParams lp = holder.tv.getLayoutParams();
        lp.height = mHeight.get(position);
        holder.tv.setLayoutParams(lp);
    }

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



    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tv;

        public MyViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
            super(itemView);
            tv = (TextView)itemView.findViewById(R.id.tv_item);
        }

    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
        void onItemLongClick(View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener myOnItemClickListener){
        this.mOnItemClickListener = myOnItemClickListener;
    }

}

activity_recycler_test.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/id_recyclerview"
        android:divider="#ffb900"
        android:dividerHeight="1sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

item_recycler.xml file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="moon"
        android:background="#A3A3A3"/>

</FrameLayout>

Second, the implementation of Grid

The effect is as follows:

 Add the following code to the useRecyclerView method of the RecyclerViewTest code:

        /*
        实现GridView功能
         */
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
                StaggeredGridLayoutManager.VERTICAL));
        recyclerView.addItemDecoration(new DividerItemDecoration(this));

3. Realization of Waterfall

The effect is as follows:

 1. Define the split distance in item_recycler as 2dp

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="2dp"
    android:background="@color/white">

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="moon"
        android:background="#A3A3A3"/>

</FrameLayout>

2. Modify the adapter HomeAdapter code:

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

    private List<String> mList;
    private Context mContext;
    private OnItemClickListener mOnItemClickListener;
    List<Integer> mHeight; //设置随机高度





    public HomeAdapter(List<String> mList, Context mContext) {
        this.mList = mList;
        this.mContext = mContext;
        mHeight = new ArrayList<Integer>();
        for (int i = 0; i < mList.size(); i++) {
            mHeight.add((int)(100 + Math.random() * 300));
        }
    }

    public void removeData(int position){
        mList.remove(position);
        notifyItemRemoved(position);
    }



    @NonNull
    @NotNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        MyViewHolder holder =
                new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_recycler,parent,false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull HomeAdapter.MyViewHolder holder, int position) {
        holder.tv.setText(mList.get(position));
        if (mOnItemClickListener != null){
            holder.tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.tv,pos);
                }
            });

            holder.tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemLongClick(holder.tv,pos);
                    return false;
                }
            });
        }

        //瀑布流实现
        ViewGroup.LayoutParams lp = holder.tv.getLayoutParams();
        lp.height = mHeight.get(position);
        holder.tv.setLayoutParams(lp);
    }

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



    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tv;

        public MyViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
            super(itemView);
            tv = (TextView)itemView.findViewById(R.id.tv_item);
        }

    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
        void onItemLongClick(View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener myOnItemClickListener){
        this.mOnItemClickListener = myOnItemClickListener;
    }

}



Guess you like

Origin blog.csdn.net/weixin_55512999/article/details/126117772