GridLayout 使用总结

本文详细介绍了Android中的GridLayout布局,包括其常用属性、平分问题解决方案及如何实现类似小米计算器的效果,并提供了动态加载实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介


GridLayout是Android4.0引入的网格布局,使用它可以减少布局嵌套。也算是常用,但一直没仔细看过,今天研究一下

二、常用属性介绍


GridLayout 使用属性

属性作用
android:columnCount最大列数
android:rowCount最大行数
android:orientationGridLayout中子元素的布局方向
android:alignmentModealignBounds:对齐子视图边界 alignMargins :对齐子视距内容,默认值
android:columnOrderPreserved使列边界显示的顺序和列索引的顺序相同,默认是true
android:rowOrderPreserved使行边界显示的顺序和行索引的顺序相同,默认是true
android:useDefaultMargins没有指定视图的布局参数时使用默认的边距,默认值是false

item属性

属性作用
android:layout_column指定该单元格在第几列显示
android:layout_row指定该单元格在第几行显示
android:layout_columnSpan指定该单元格占据的列数
android:layout_rowSpan指定该单元格占据的行数
android:layout_gravity指定该单元格在容器中的位置
android:layout_columnWeight(API21加入)列权重
android:layout_rowWeight(API21加入) 行权重
android:layout_gravity作用
center不改变元素的大小,仅居中
center_horizontal不改变大小,水平居中
center_vertical不改变大小,垂直居中
top不改变大小,置于顶部
left不改变大小,置于左边
bottom不改变大小,置于底部
right不改变大小,置于右边
start不改变大小,根据系统语言,置于开始位置
end不改变大小,置于结尾
fill拉伸元素控件,填满其应该所占的格子
fill_vertical仅垂直方向上拉伸填充
fill_horizontal仅水平方向上拉伸填充
clip_vertical垂直方向上裁剪元素,仅当元素大小超过格子的空间时
clip_horizontal水平方向上裁剪元素,仅当元素大小超过格子的空间时

注意

使用layout_columnSpanlayout_rowSpan时要加上layout_gravity属性,否则没有效果;另外item在边缘时宽高计算会出现错误,需要我们手动设置宽高,否则达不到想要的效果

三、平分问题


GridLayout在API21时引入了android:layout_columnWeightandroid:layout_rowWeight来解决平分问题

那么在API21以前的,想要平分的话:引用兼容包

compile 'com.android.support:gridlayout-v7:25.+'

注意:

  1. 使用该控件,命名空间使用app
  2. 单独设置app:layout_columnWeight时,这一列的所有item都设置为这个属性,才能达到预期效果,否则这一列中设置了该属性的item,都会被隐藏,显示不出来
  3. 单独设置app:layout_rowWeight时,没有问题

四、小米计算器效果


<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/grid_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ece7e7"
    app:alignmentMode="alignBounds"
    app:columnCount="4"
    app:orientation="horizontal"
    app:rowCount="5"
    app:useDefaultMargins="false"
    tools:context="com.strivestay.gridlayoutdemo.MainActivity">

    <!-- 如果不使用 app:layout_gravity="fill",
        则实际下面这个textview的宽度只是wrap_content,
        实现不了想要的right|bottom效果;
        或者,
        用app:layout_columnWeight="1",
        效果等同,填充满
    -->
    <TextView
        android:gravity="right|bottom"
        android:text="0"
        app:layout_columnSpan="4"
        app:layout_rowWeight="3"
        app:layout_columnWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="AC"
        android:textColor="#f68904"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="退格"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="/"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="*"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="7"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="8"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="9"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="—"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="4"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="5"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="6"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="+"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="1"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="2"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="3"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#f68904"
        android:gravity="center"
        android:text="="
        android:textColor="#ffffff"
        app:layout_columnWeight="1"
        app:layout_rowSpan="2"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="%"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="0"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>

    <TextView
        android:layout_margin="1dp"
        android:background="#ffffff"
        android:gravity="center"
        android:text="."
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"/>


</android.support.v7.widget.GridLayout>

效果: 4.4.4模拟器

五、动态加载


1.xml引用GridLayout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/grid_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ece7e7"
    app:orientation="horizontal"
    app:useDefaultMargins="false"
    app:alignmentMode="alignBounds"
    tools:context="com.strivestay.gridlayoutdemo.MainActivity">

</android.support.v7.widget.GridLayout>

2.动态添加

package com.strivestay.gridlayoutdemo;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayout;
import android.view.Gravity;
import android.widget.TextView;
/**
 * GridLayout示例
 * @author StriveStay
 * @date 2018/3/27
 */
public class MainActivity extends AppCompatActivity {

    private String[] mStrings = {"0","AC","退格","/","*","7","8","9","—","4","5","6","+","1","2","3","=","%","0","."};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // xml布局
//        setContentView(R.layout.activity_main);

        // 动态添加
        setContentView(R.layout.activity_main2);

        GridLayout gridLayout = (GridLayout) findViewById(R.id.grid_layout);

        // 6行   4列
        gridLayout.setColumnCount(4);
        gridLayout.setRowCount(6);

        for (int i = 0; i < mStrings.length; i++) {
            TextView textView = new TextView(this);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width =0;
            params.height =0;

            if(i == 0){
                // 设置行列下标, 所占行列  ,比重
                // 对应: layout_row  , layout_rowSpan , layout_rowWeight
                // 如下代表: item坐标(0,0), 占 1 行,比重为 3 ; 占 4 列,比重为 1
                params.rowSpec = GridLayout.spec(0,1,3f);
                params.columnSpec = GridLayout.spec(0,4,1f);

                textView.setGravity(Gravity.BOTTOM|Gravity.RIGHT);
            }else{
                // 设置行列下标,和比重
                params.rowSpec = GridLayout.spec((i+3)/4,1f);
                params.columnSpec = GridLayout.spec((i+3)%4,1f);

                // 背景
                textView.setBackgroundColor(Color.WHITE);

                // 字体颜色
                if("AC".equals(mStrings[i])){
                    textView.setTextColor(Color.parseColor("#f68904"));
                }

                if("=".equals(mStrings[i])){
                    textView.setBackgroundColor(Color.parseColor("#f68904"));
                    textView.setTextColor(Color.WHITE);
                    params.rowSpec = GridLayout.spec((i+3)/4,2,1f);
                }
                
                // 居中显示
                textView.setGravity(Gravity.CENTER);

                // 设置边距
                params.setMargins(2,2,2,2);
            }

            // 设置文字
            textView.setText(mStrings[i]);

            // 添加item
            gridLayout.addView(textView,params);
        }
    }
}

效果和用xml中直接布局一样:

注意:
GridLayout.spec(); 这个方法是一个重点,需要好好看一下,而且由于它有几个重载方法,使用时也要注意。比如说下面两个方法:

 public static Spec spec(int start, int size)
 public static Spec spec(int start, float weight)

我刚开始就忽略了这点,本想用的是第二个带有weight的方法,但是传入参数时,没有加上f,就调用了第一个方法,搞了半天才发现

所以,如果调用的是第二个方法,一定要注意float参数的表示方法,加个f,如:GridLayout.spec(0,1f);

<think>首先,用户的问题是:“我想了解GridLayout的详细用法和原理请问GridLayout详细用法及实现原理”。用户引用了几个来源,但这些只是上下文,我应该基于提供的引用和自己的知识来回答。引用[1]到[5]包括关于GridLayout的讨论,特别是从引用[2]、[3]、[4]中提到了GridLayoutAndroid中的应用。用户引用的关键点:-引用[2]:讨论了GridLayoutAndroid5.1及以后使用权重属性,以及为API21之前的设备使用支持库。-引用[3]:提到了使用post()方法获取视图宽高,这可能适用于GridLayout的子视图。-引用[4]:解释GridLayoutAndroid4.0后推出的,需要支持库来兼容低版本。-引用[5]:关于内存管理,但与GridLayout直接相关不强。用户的问题聚焦在GridLayout的详细用法和原理,所以我需要提供一个结构化的回答,包括用法(如布局方式、属性)和实现原理(如网格布局的工作原理)。系统级指令:-所有行内数学表达式使用$...$格式。在这个上下文中,可能不会有数学表达式,因为话题是AndroidUI布局。所以,我可能不需要它,但如果有任何公式或变量,要用这个格式。-独立公式用$$...$$并单独成段。-LaTeX语法正确。-使用中文回答。-生成相关问题。-在引用的段落末尾添加引用标识,如[^1]。我应该参考用户提供的引用来支持我的回答。-回答结构清晰,逐步解决问题。-保证真实可靠。用户上一次问题是查询GridLayout,引用了多个来源,我需要尽可能多参考这些引用。结构化回答:1.**介绍GridLayout**:解释什么是GridLayout,它在Android中的目的。2.**详细用法**:-如何使用XML定义GridLayout。-常见属性:如列数、行数、权重(特别是android:layout_columnWeight和android:layout_rowWeight)。-兼容性处理:使用支持库(v7gridlayout)为低版本Android。-例子代码,参考引用[2]和[4]。3.**实现原理**:-GridLayout如何布局组件:分配空间、对齐方式。-内部工作原理,如使用网格单元格、处理权重。-参考引用[3]提到获取视图宽高的方式,可能与GridLayout的布局计算相关。-内存或性能方面,简要提及引用[5],但不直接相关。4.**优势和局限性**:参考引用[1],提到GridLayout的规则性。5.**总结**。6.**生成相关问题**:类似于示例。引用标识:我需要在回答中引用时添加,如[^2]或[^4],基于提供的引用。用户提供了[^1]到[^5],所以我可以引用它们。用中文回答。大纲回答:-**开头**:简要介绍GridLayout。-**用法部分**:-XML定义:`<GridLayout>`元素。-属性:columnCount,rowCount,orientation。-权重属性:layout_columnWeight,layout_rowWeight(需要支持库或API21+)。-兼容性:使用android.support.v7.widget.GridLayout和布局属性如app:layout_columnWeight。-示例XML代码。-在代码中获取视图:参考引用[3]的post()方法。-**原理部分**:-GridLayout通过网格系统布局组件,平均分配空间或按权重。-实现方式:在视图树遍历时计算位置和大小。-针对低版本的支持库实现。-**总结**。-**相关问题**。确保真实可靠:基于Android开发知识,参考API文档和提供引用。生成相关问题:例如:1.GridLayout和TableLayout的区别?2.如何处理GridLayout中的动态添加或删除组件?3.GridLayout的性能考虑?引用添加:-在描述权重属性时,引用[^2]。-在兼容性部分,引用[^4]。-在视图宽高获取时,引用[^3]。</think> ### GridLayout详细用法及实现原理 GridLayoutAndroid布局管理器之一,用于将UI组件排列在规则的行列网格中,特别适用于需要整齐对齐的场景(如表格界面)。下面我将基于您的引用内容和我自己的知识,从用法和原理两方面逐步解释。 #### 一、GridLayout的详细用法 GridLayout用法主要包括XML布局定义、属性设置和Java代码控制。核心是**行与列的规则划分**,确保组件均匀分布。以下是关键用法: 1. **XML布局定义**: - 使用`<GridLayout>`元素在布局文件中定义网格。默认情况下,GridLayout会根据组件数量自动推断行列结构,但您可以手动设置。 - 基本结构示例(参考引用[4]兼容方式): ```xml <!-- Android 4.0+原生使用 --> <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:columnCount="3" <!-- 设置列数 --> android:rowCount="2"> <!-- 设置行数 --> <Button android:text="按钮1" android:layout_row="0" <!-- 指定行位置 --> android:layout_column="0"/> <!-- 指定列位置 --> <Button android:text="按钮2" android:layout_row="0" android:layout_column="1"/> </GridLayout> ``` - 属性说明: - `android:columnCount` 和 `android:rowCount`:定义网格的总列数和行数。 - `android:layout_row` 和 `android:layout_column`:指定组件放置的起始位置(从0开始)。 - `android:layout_gravity`:可选,设置组件在单元格内的对齐方式(如居中)。 2. **权重属性(Weight)实现自适应布局**: - GridLayout支持按权重分配空间,使单元格大小均匀。但权重属性仅在Android 5.1 (API 21)及以上版本原生支持(引用[2])。 - 权重属性:`android:layout_columnWeight`和`android:layout_rowWeight`,允许组件根据权重比例分配空间。 - **兼容低版本(API < 21)**:必须使用Support库(v7 gridlayout),参考引用[2]和[4]。 - 添加依赖:在build.gradle中引入`com.android.support:gridlayout-v7:22.+`或更新版本。 - XML定义: ```xml <!-- API 21以下使用支持库 --> <android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" app:columnCount="3" app:rowCount="2"> <Button android:text="按钮1" app:layout_row="0" app:layout_column="0" app:layout_columnWeight="1"/> <!-- 权重属性 --> </android.support.v7.widget.GridLayout> ``` - 注意:权重值可以是任何正数(例如$1$表示均等分配),系统会根据总值计算比例[^2][^4]。 3. **动态添加组件和获取尺寸**: - **视图宽高获取**:GridLayout在布局时可能无法在`onCreate()`中直接获取子视图宽高(因为它依赖父视图尺寸)。需使用`post()`方法(参考引用[3]): ```java GridLayout gridLayout = findViewById(R.id.grid_layout); gridLayout.post(new Runnable() { @Override public void run() { int width = gridLayout.getWidth() / gridLayout.getColumnCount(); // 单元格宽 int height = gridLayout.getHeight() / gridLayout.getRowCount(); // 单元格高 // 用于添加组件或初始化 Button button = new Button(this); gridLayout.addView(button); } }); ``` - 此方法确保在视图渲染完成后再计算,避免空指针错误[^3]。 - **添加组件**:可在Java代码中动态增加行或列,但需注意网格大小变化时可能重新计算布局。 4. **常见问题与优化**: - **溢出处理**:如果组件数超过行列定义,GridLayout会自动扩展网格(例如3列变4列)。这可能导致布局凌乱,建议固定行列数或使用权重。 - **性能注意**:GridLayout布局计算简单(时间复杂度$O(n)$,$n$是组件数),比复杂布局如RelativeLayout高效[^5]。但组件多时,权重计算可能增加CPU开销。 #### 二、GridLayout的实现原理 GridLayout的核心原理是**网格空间分配和组件位置计算**,基于Android的视图系统。以下是关键原理点: 1. **布局计算过程**: - GridLayout通过两次遍历完成布局: - **测量(Measure)**:计算每个单元格的理想大小。如果使用权重,系统先计算总权重,再按比例分配空间(例如总权重$W_{\text{total}} = \sum w_i$,单元格大小$s_i = \frac{w_i}{W_{\text{total}}} \times \text{parentSize}$)。 - **布局(Layout)**:根据行列位置将组件放置在精确坐标上。算法考虑对齐属性(如Gravity),确保组件在单元格内居中或对齐边缘。 - 例如,没有权重时,GridLayout平分空间;有权重时,空间分配遵守$\text{大小比例} = \frac{w_i}{W_{\text{total}}}}$[^2]。 2. **内存与性能机制**: - GridLayout继承自ViewGroup,共享Android布局管道的机制。在内部,它使用稀疏数组存储组件位置,减少内存占用(引用[5]提到每个APP的内存上限,但GridLayout自身轻量)。 - **权重实现的兼容性**:Support库的GridLayout(v7)在低版本上通过Java代码模拟权重计算,而非原生渲染,这增加了少量开销但保证一致性[^4]。 3. **优势和局限性**: - **优势**:规则布局易于控制,适合均等大小组件(如按钮矩阵或图片网格);权重属性实现响应式设计。 - **局限性**:灵活性低,组件必须适配单元格,不适复杂嵌套布局(FlowLayout更适合自由排列,参考引用[1])。在行或列数变化频繁时,性能可能下降。 #### 三、总结 GridLayout是一个高效的规则布局工具,通过行列网格和权重属性简化UI设计。在Android 5.1+可直接使用权重,低版本需Support库兼容。原理上,它基于网格空间分配算法,确保组件均匀分布。正确使用时(如固定行列、权重优化),能提升界面一致性和性能[^2][^4]。 如果您想深入,我建议查阅Android官方文档或在代码中实验权重效果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值