问题描述
我正在构建一个使用 RecyclerView
的 android 应用程序.我想在 RecyclerView
中添加分隔符,这是我使用以下代码完成的:
i am building an android app which is using RecyclerView
. I want to add dividers to RecyclerView
, which I did using this code:
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
到目前为止一切正常.但是,分隔符占用了全屏的大小,我想为其添加边距.有什么方法可以使用一种方法来为分隔线添加边距,该方法将为绘制的矩形添加一些空间,而不是通过创建带有边距的自定义可绘制形状并将其添加到 RecyclerView
中?>
So far everything works fine. However, the divider is taking the size of full screen and I want to add margins to it. Is there any way that I can add margins to the divider using a method that will add some space to the rectangle drawn and not by creating a custom drawable shape with margins and add it to the RecyclerView
?
推荐答案
使用它并根据您的要求进行自定义.
Use this and customize according to your requirement.
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);
}
}
}
这篇关于在 RecyclerView 中为分隔线添加边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!