GridView中的方形项目,具有自适应宽度/高度

use*_*095 8 android gridview

我有一个自定义gridview与这样的项目

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center"
android:longClickable="false"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:longClickable="false"
    android:text="0"
    android:textSize="60sp" />

 </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我希望我的项目是正方形,我希望gridview拉伸宽度以纵向填充屏幕的所有宽度和横向的所有高度.它看起来应该是这样的 布局

其中A - 是正方形的边,B是边距宽度(可以是零).我认为我应该覆盖onMeasure方法,但究竟应该怎么做?也许有人可以帮忙吗?

编辑确定,我试图在适配器的getView方法中手动设置项目的宽度和高度,它更好,但它仍然不是我想要的.如何摆脱列之间的间距?

在此输入图像描述

Ser*_*kyi -1

所以你需要GridView适合屏幕的stretchMode="columnWidth"stretchMode="rowWidth"。不幸的是,最后一个不是真正的属性,您实际上需要在运行时进行此计算,正如 Sherif elKhatib 所建议的那样。

GridView 会自动适应屏幕并拉伸列。

<GridView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchMode="columnWidth" />
Run Code Online (Sandbox Code Playgroud)

所以我们只需要拉伸行即可。如果我们知道 GridView 和 rowsCount 的高度,我们可以通过计算 rowHeight 应该是多少来做到这一点。

public class YourAdapter extends BaseAdapter {

   int rowsCount;

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {

       View itemView = convertView;
       if (itemView == null) {
           itemView = layoutInflater.inflate(R.layout.item_view, parent, false);            
           int height = parent.getHeight();
           if (height > 0) {
               LayoutParams layoutParams = itemView.getLayoutParams();
               layoutParams.height = (int) (height / rowsCount);
           } // for the 1st item parent.getHeight() is not calculated yet       
       }
   }
}
Run Code Online (Sandbox Code Playgroud)