【发布时间】:2016-02-23 10:29:15
【问题描述】:
我想要一个正方形(与高度相同的宽度)GridView 以横向填充屏幕的整个高度。 Gridview 是一个带有 xml 的棋盘(8 x 8 方格):
<com.example.jens.jchess2.view.MyGridView
android:id="@+id/chessboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp"
android:numColumns="8"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp">
</com.example.jens.jchess2.view.MyGridView>
而网格的元素是:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/square"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000080"
android:orientation="vertical"
android:padding="0pt">
<ImageView
android:id="@+id/square_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:padding="0pt" />
<ImageView
android:id="@+id/piece"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:padding="0pt" />
</FrameLayout>
,其中 ImageViews 对应于棋盘的正方形和棋子(均来自 png 图像)。
在自定义 MyGridView 中,我按如下方式覆盖 onMeasure:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = getContext().getResources().getDisplayMetrics().heightPixels;
if (width > height) {
super.onMeasure(
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
);
} else {
super.onMeasure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)
);
}
}
这给了我一个纵向和横向的方形 GridView。在纵向模式下,它会填满整个宽度,一切都很好。但是在横向模式下,它会延伸到屏幕下方,因为 GridView/board 的高度(=宽度)太大。工具栏的高度和状态栏的高度太大了。如何获得合适的 GridView 尺寸,即屏幕高度减去状态栏高度减去工具栏高度?
【问题讨论】:
-
使 heightMeasureSpec 等于窗口高度 ....
标签: android android-layout gridview landscape-portrait