我的 GridView 包含固定宽度的列,具有固定的水平间距。如果没有足够的列来水平填充屏幕,我希望我的 GridView 的宽度能够包裹到它的内容,并在屏幕中垂直居中。
但是,无论我使用多少列,GridView 的宽度都会增长以填满屏幕。所附图像显示了这一点,其中绿色 GridView 水平填充屏幕,尽管只有 3 列并且其宽度设置为“wrap_content”。
public class Temp extends Activity
{
private GridView grid;
private int columnWidth = 80;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = getLayoutInflater().inflate(R.layout.gridview, null);
grid = (GridView) view.findViewById(R.id.grid);
grid.setColumnWidth(columnWidth);
grid.setAdapter(new GridAdapter());
setContentView(view);
}
class GridAdapter extends BaseAdapter
{
public GridAdapter()
{
}
public int getCount()
{
return 3;
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView (int position, View convertView, ViewGroup parent)
{
View ret;
if (convertView == null)
{
ret = new ImageView(Temp.this);
ret.setLayoutParams(new GridView.LayoutParams(columnWidth, 100));
ret.setBackgroundColor(Color.WHITE);
}
else
{
ret= convertView;
}
return ret;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FF0000"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/grid"
android:background="#00FF00"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="auto_fit"
android:verticalSpacing="2dip"
android:horizontalSpacing="2dip"
android:stretchMode="columnWidth"
android:gravity="center">
</GridView>
</RelativeLayout>