package com.gingersoft.gsa.cloud.ui.recylcler.decorator;

import android.graphics.Rect;
import android.util.Log;
import android.view.View;

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

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/1/15
 * Time: 18:57
 * Use: 解決的問題：例：第一個item距離頂部5dp，最後一個item距離底部5dp，設置margin為5，
 * 那第二個item就距離第一個item10dp了
 */
public class MarginDecoration extends RecyclerView.ItemDecoration {

    private int marginTop;

    public MarginDecoration(int marginTop) {
        this.marginTop = marginTop;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        // 得到当前Item在RecyclerView中的位置,从0开始
        int position = parent.getChildAdapterPosition(view);
        // 得到RecyclerView中Item的总个数
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter != null) {
            int count = parent.getAdapter().getItemCount();
            if (parent.getLayoutManager() instanceof GridLayoutManager) {
                //網格佈局
                if (position == count - 1) {
                    outRect.left = marginTop;
                }
                outRect.right = marginTop;
            } else if (parent.getLayoutManager() instanceof LinearLayoutManager) {
                if (position == count - 1) {
                    outRect.bottom = marginTop;
                }
                outRect.top = marginTop;
            }
        }
    }
}
