Android RecyclerView设置间距
我现在要完成这个图形
recycleview默认是没有间距的,我们要手动设置
rl_daily.setLayoutManager(new GridLayoutManager(getContext(), 3)); recycleViewAdapter = new RecycleViewAdapter(list); rl_daily.setAdapter(recycleViewAdapter); //设置边距 rl_daily.addItemDecoration(new RecycleItemsDecortion.SpaceItemDecoration(0, 15));
适配器
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> { private List<Object> list; private int parentWidth; public RecycleViewAdapter(List<Object> list) { this.list = list; } class MyViewHolder extends RecyclerView.ViewHolder { private TextView tv_username; public MyViewHolder(View itemView) { super(itemView); // tv_username = (TextView) itemView.findViewById(R.id.tv_user_tag); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tk3100_daily_recyle_adapter, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { //holder.tv_username.setText(String.valueOf(list.get(position))); } @Override public int getItemCount() { return list.size(); } }
设置间距的代码
//设置边距 public static class SpaceItemDecoration extends RecyclerView.ItemDecoration { private final int normal; private final int margin; @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.top = normal; outRect.bottom = normal; if (parent.getChildAdapterPosition(view) % 3 == 0) { outRect.right = normal; outRect.left = margin; } else if (parent.getChildAdapterPosition(view) % 3 == 1) { outRect.right = margin; outRect.left = margin; } else if (parent.getChildAdapterPosition(view) % 3 == 2) { outRect.right = normal; outRect.left = margin; } } public SpaceItemDecoration(int normal, int margin) { this.normal = normal; this.margin = margin; } }