如何强制 android GridView 生成方形单元格(单元格的高度等于单元格的宽度) GridView 有 10*9 个单元格,应用必须支持多屏!
我使用了线性布局:
row_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp" >
<ImageView
android:id="@+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" >
</ImageView>
</LinearLayout>
和 GridView: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/katy" >
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="0dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp" >
</GridView>
</RelativeLayout>
GridView 的每个单元格都包含一个具有相同宽度和高度的图像。 图像比单元格大,必须拉伸(stretch)以适应单元格。
最佳答案
首先,您需要创建一个可以使用的自定义 View 类,而不是您正在使用的默认 LinearLayout。然后你想覆盖 View 的 onMeasure 调用,并强制它是方形的:
public class GridViewItem extends ImageView {
public GridViewItem(Context context) {
super(context);
}
public GridViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
}
}
然后您可以将 row_grid.xml 文件更改为:
<path.to.item.GridViewItem xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher" >
</path.to.item.GridViewItem>
请务必将“path.to.item”更改为 GridViewItem.java 类所在的包。
我还删除了您的 LinearLayout 父级,因为它在那里没有为您做任何事情。
编辑:
还将 scaleType 从 fitXY 更改为 centerCrop,这样您的图像就不会自行拉伸(stretch)并保持其纵横比。而且,只要是方形图像,无论如何都不应裁剪。
关于android - 如何强制GridView在Android中生成方形单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416847/