要将HorizontalGridView设置为wrap_content,您可以按照以下步骤进行操作:
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spacing;
public GridSpacingItemDecoration(int spacing) {
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = spacing;
outRect.right = spacing;
outRect.bottom = spacing;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = spacing;
} else {
outRect.top = 0;
}
}
}
HorizontalGridView horizontalGridView = findViewById(R.id.horizontalGridView);
GridLayoutManager layoutManager = new GridLayoutManager(this, numberOfColumns);
horizontalGridView.setLayoutManager(layoutManager);
// 设置间距
int spacing = getResources().getDimensionPixelOffset(R.dimen.grid_spacing);
GridSpacingItemDecoration itemDecoration = new GridSpacingItemDecoration(spacing);
horizontalGridView.addItemDecoration(itemDecoration);
通过以上步骤,您可以将HorizontalGridView设置为wrap_content,并且应用间距使其适应您的需求。
上一篇:Android:如何将GridView选中的图像插入到SqlLite中
下一篇:Android:如何将HTML字符串转换为Spanned以在TextView中显示(必须适用于API < 24)