这是我的解决方案。
public class ResponsiveGridLayoutManager extends GridLayoutManager {
boolean hasSetupColumns;
int columnWidthPx;
public ResponsiveGridLayoutManager(Context context, int orientation,
boolean reverseLayout, int columnWidthUnit, float columnWidth) {
super(context, 1, orientation, reverseLayout);
Resources r;
if (context == null) {
r = Resources.getSystem();
} else {
r = context.getResources();
}
float colWidthPx = TypedValue.applyDimension(columnWidthUnit,
columnWidth, r.getDisplayMetrics());
this.columnWidthPx = Math.round(colWidthPx);
}
public ResponsiveGridLayoutManager(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
int[] requestedValues = {
android.R.attr.columnWidth,
};
TypedArray a = context.obtainStyledAttributes(attrs, requestedValues);
this.columnWidthPx = a.getDimensionPixelSize(0, -1);
a.recycle();
}
@Override
public int getWidth() {
int width = super.getWidth();
if (!hasSetupColumns && width > 0) {
this.setSpanCount((int)Math.floor(width / this.columnWidthPx));
}
return width;
}
}
您可以将它与 XML 一起使用:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="com.caff.localflix.ResponsiveGridLayoutManager"
android:columnWidth="148dp" />
或 Java:
ResponsiveGridLayoutManager layoutManager = new ResponsiveGridLayoutManager(
this,
GridLayoutManager.VERTICAL,
false,
TypedValue.COMPLEX_UNIT_DIP,
148f
);