天天看點

Android RecyclerView設定間距

我現在要完成這個圖形

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