这是 GridLayout 的自定义实现,可以满足您的需求:AutoGridLayout
public class AutoGridLayout extends GridLayout {
private int defaultColumnCount;
private int columnWidth;
public AutoGridLayout(Context context) {
super(context);
init(null, 0);
}
public AutoGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public AutoGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr);
}
private void init(AttributeSet attrs, int defStyleAttr) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.AutoGridLayout, 0, defStyleAttr);
try {
columnWidth = a.getDimensionPixelSize(R.styleable.AutoGridLayout_columnWidth, 0);
int[] set = { android.R.attr.columnCount /* id 0 */ };
a = getContext().obtainStyledAttributes(attrs, set, 0, defStyleAttr);
defaultColumnCount = a.getInt(0, 10);
} finally {
a.recycle();
}
/* Initially set columnCount to 1, will be changed automatically later. */
setColumnCount(1);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
int width = MeasureSpec.getSize(widthSpec);
if (columnWidth > 0 && width > 0) {
int totalSpace = width - getPaddingRight() - getPaddingLeft();
int columnCount = Math.max(1, totalSpace / columnWidth);
setColumnCount(columnCount);
} else {
setColumnCount(defaultColumnCount);
}
}
}
只需像这样添加到您的 XML 布局文件中:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.km.myproject.customview.AutoGridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="5"
app:columnWidth="50dp"/>
</FrameLayout>
使用columnWidth 将尝试计算可以容纳多少列并自动设置最佳跨度计数。如果不使用(或由于某种原因未能测量),将使用columnCount 属性。
希望这会有所帮助!