Добавить поля для разделителя в RecyclerView
Я создаю приложение для Android, которое использует RecyclerView
. Я хочу добавить разделители в RecyclerView
, который я использовал с помощью этого кода:
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
Пока все работает нормально. Однако делитель принимает размер полного экрана, и я хочу добавить к нему поля. Есть ли способ, которым я могу добавить поля в разделитель, используя метод, который добавит некоторое пространство в рисованный прямоугольник, а не путем создания настраиваемой фигуры с полями и добавит ее в RecyclerView
?
Ответы
Ответ 1
Используйте это и настройте в соответствии с вашими требованиями.
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable divider;
/**
* Default divider will be used
*/
public DividerItemDecoration(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
divider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
/**
* Custom divider will be used
*/
public DividerItemDecoration(Context context, int resId) {
divider = ContextCompat.getDrawable(context, resId);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + divider.getIntrinsicHeight();
divider.setBounds(left, top, right, bottom);
divider.draw(c);
}
}
}
Ответ 2
Я думаю, что наиболее простым решением является использование метода setDrawable на объекте "Украшение" и передать ему вставку с допустимыми значениями вставки, которые вы хотите для полей. Например:
int[] ATTRS = new int[]{android.R.attr.listDivider};
TypedArray a = context.obtainStyledAttributes(ATTRS);
Drawable divider = a.getDrawable(0);
int inset = getResources().getDimensionPixelSize(R.dimen.your_margin_value);
InsetDrawable insetDivider = new InsetDrawable(divider, inset, 0, inset, 0);
a.recycle();
DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
itemDecoration.setDrawable(insetDivider);
recyclerView.addItemDecoration(itemDecoration);
Ответ 3
Вы можете создать собственное украшение элемента для просмотра ресайклеров.
Вот код для того же самого.
public class SimpleItemDecorator extends RecyclerView.ItemDecoration {
int space;
boolean isHorizontalLayout;
public SimpleItemDecorator(int space) {
this.space = space;
}
public SimpleItemDecorator(int space, boolean isHorizontalLayout) {
this.space = space;
this.isHorizontalLayout = isHorizontalLayout;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if(isHorizontalLayout)
{
outRect.bottom=space;
outRect.right=space;
outRect.left=space;
outRect.top=space;
} else {
outRect.bottom = space;
if (parent.getChildAdapterPosition(view) == 0)
outRect.top = space;
else
outRect.top = 0;
}
}
}
И чтобы использовать его с вашим recyclerview, вы можете сделать вот так:
recyclerView.addItemDecoration(new SimpleItemDecorator(5));
Ответ 4
То же самое, что и ответ @Vivek, но в Kotlin и других параметрах
class SimpleItemDecorator : RecyclerView.ItemDecoration {
private var top_bottom: Int = 0
private var left_right: Int = 0
/**
* @param top_bottom for top and bottom margin
* @param left_right for left and right margin
*/
constructor(top_bottom: Int, left_right: Int = 0) {
this.top_bottom = top_bottom
this.left_right = left_right
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
outRect.bottom = top_bottom
outRect.top = top_bottom
outRect.right = left_right
outRect.left = left_right
}
}