我在我的应用中使用GridView:
<GridView
android:id="@+id/main_grid_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4" >
</GridView>
此GridView中的每个单元格都是ImageView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:contentDescription="@string/img"
android:scaleType="centerCrop" />
</RelativeLayout>
我的GridView中的所有单元格必须是正方形(高度必须等于宽度),并且图像必须适合单元格。但它总是看起来像矩形......我怎么能在GridView中实现方形单元?
答案 0 :(得分:1)
确保您的手机正方形。
为此,您可以使用值screen_width / 4以编程方式设置RelativeLayout的宽度和高度。
答案 1 :(得分:0)
这可以解决问题
@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}
答案 2 :(得分:0)
正如答案中所述 - Gridview with two columns and auto resized images
您可以为此
制作自定义ImageViewpublic class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public SquareImageView(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
} else {
setMeasuredDimension(getMeasuredHeight(), getMeasuredHeight());
}
}
}
然后在网格视图单元格布局中使用它
<package_containing_SquareImageView.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent" />