【发布时间】:2019-06-19 05:10:34
【问题描述】:
我试图在RecyclerView 的项目之间放置相等的空间。为此,我使用下面的SpanningLinearLayoutManager。它的作用是,它会在RecyclerView 中的项目之间自动分配空间,但它会使RecyclerView 不可滚动。所有项目都将在父项的宽度内。这适用于 5 或 6 个项目。但是如果列表有大约 10 个元素,那么所有元素都会非常接近。我想平均分配项目之间的空间并使recyclerview 可滚动方式。
我在父母RecyclerView 中有一个孩子RecyclerView。我想在孩子RecyclerView的项目之间平均分配空间@
这是我的代码:
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.ViewGroup;
public class SpanningLinearLayoutManager extends LinearLayoutManager {
public SpanningLinearLayoutManager(Context context) {
super(context);
}
public SpanningLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public SpanningLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return spanLayoutSize(super.generateDefaultLayoutParams());
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return spanLayoutSize(super.generateLayoutParams(c, attrs));
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
return spanLayoutSize(super.generateLayoutParams(lp));
}
@Override
public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
return super.checkLayoutParams(lp);
}
private RecyclerView.LayoutParams spanLayoutSize(RecyclerView.LayoutParams layoutParams){
if(getOrientation() == HORIZONTAL){
layoutParams.width = (int) Math.round(getHorizontalSpace() / (double) getItemCount());
}
else if(getOrientation() == VERTICAL){
layoutParams.height = (int) Math.round(getVerticalSpace() / (double) getItemCount());
}
return layoutParams;
}
@Override
public boolean canScrollVertically() {
return false;
}
@Override
public boolean canScrollHorizontally() {
return false;
}
private int getHorizontalSpace() {
return getWidth() - getPaddingRight() - getPaddingLeft();
}
private int getVerticalSpace() {
return getHeight() - getPaddingBottom() - getPaddingTop();
}
}
【问题讨论】:
-
使用自定义 itemdecoration 设置项目之间的间距
-
任何示例的链接? @Raghunandan
-
@nTri 没有用。所有项目都在开始时对齐。我在另一个
recyclerview中使用recyclerview。
标签: android android-recyclerview