效果:
一、自定义设置边距方法
SpaceItemDecoration.java
package com.custom.jfrb.ui.jfrb.finishedProduct; //自己包名位置import android.graphics.Rect;
import android.view.View;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;/*** create by niuxi on 2023/9/26* 自定义类,GridLayoutManager设置边距*/
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {private int space; //边距值private int itemNum; //每行item数量public SpaceItemDecoration(int space,int itemNum) {this.space = space;this.itemNum = itemNum;}@Overridepublic void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {outRect.left = space;outRect.right = space;outRect.bottom = space;outRect.top = space;if (itemNum == 2){//一行两个时候,两个item靠近外面的那一边不设置边距if (parent.getChildLayoutPosition(view)%itemNum == 0){outRect.left = 0;}else if (parent.getChildLayoutPosition(view)%itemNum == 1){outRect.right = 0;}}}
}
二、Activity中调用设置边距
例子:给RecyclerView设置排列方式和边距
@InjectView(id = R.id.recyclerview_all_products)
private RecyclerView mRecyclerViewAllProducts;private ProductAdapter adapter;private List<FilePageBean> mList = new ArrayList<>();
重点看这里设置边距调用的方法:
//设置适配器(自定义)
adapter = new ProductAdapter();
mRecyclerViewAllProducts.setAdapter(adapter);//设置布局方式
mRecyclerViewAllProducts.setLayoutManager(new GridLayoutManager(this,2));//设置默认动画
mRecyclerViewAllProducts.setItemAnimator(new DefaultItemAnimator());//设置边距值为10 item数量为2
mRecyclerView.addItemDecoration(new SpaceItemDecoration(10,2));
mRecyclerView.setPadding(0,0,0,0);
附:自定义的适配器
R.layout.list_item是单个Item的布局xml文件(可自定义)
class ProductAdapter extends RecyclerView.Adapter<MyViewHoder> {@NonNull@Overridepublic MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {View view = View.inflate(FinishedProductActivity.this, R.layout.list_item, null);return new MyViewHoder(view);}@Overridepublic void onBindViewHolder(@NonNull FinishedProductActivity.MyViewHoder holder, int position) {FilePageBean item = mList.get(position);holder.mTvProductTitle.setText(item.getName());holder.itemView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//Item点击监听}});}@Overridepublic int getItemCount() {return mList.size();}public void refreshData(List<FilePageBean> list){mList.clear();mList.addAll(list);notifyDataSetChanged();}}static class MyViewHoder extends RecyclerView.ViewHolder {TextView mTvProductTitle;public MyViewHoder(@NonNull View itemView) {super(itemView);mTvProductTitle = itemView.findViewById(R.id.tv_product_title);}}
三、完成,Nice!