GridLayout 使用总结

一、简介


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);

  • 31
    点赞
  • 130
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我会为你提供一个简单的2048游戏的制作教程。首先,我们需要了解2048游戏的规则和玩法。 2048游戏规则: 1. 游戏界面为一个4x4的方格,每个方格里面都有一个数字。 2. 每次可以选择上下左右其中一个方向进行移动。 3. 所有数字同时向选定方向移动,如果两个相同数字碰到一起,就会合并成一个数字,数值为原数字相加。 4. 每次移动后,会在空着的方格中随机生成一个数字,数字可能是2或4。 5. 当任意一个方格里的数字达到2048时,游戏胜利。 接下来,我们将使用Android Studio来创建一个2048游戏。 步骤1:创建一个新项目 在Android Studio中,选择“Start a new Android Studio project”,并按照向导的指导创建一个新项目。您可以使用任何名称和包名,但是确保最低SDK版本为21。 步骤2:创建游戏布局 我们需要创建一个包含16个方格的游戏布局。在res/layout文件夹中创建一个名为game_board.xml的新布局文件,并添加以下代码: ``` <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/game_board" android:layout_width="match_parent" android:layout_height="match_parent" android:rowCount="4" android:columnCount="4" android:background="@color/game_board_background"> <TextView android:id="@+id/tile_1" android:layout_width="0dp" android:layout_height="0dp" android:layout_row="0" android:layout_column="0" android:layout_margin="4dp" android:gravity="center" android:textSize="32sp" android:background="@drawable/tile_background" android:textColor="@color/tile_text_color" android:text="2"/> <!-- Add 15 more tiles here --> </GridLayout> ``` 这个布局文件创建了一个4x4的GridLayout,并将每个方格定义为一个TextView。每个方格都有一个唯一的ID,以及一个背景色和文本颜色。我们还将在后面创建一个名为tile_background的XML文件,它将为每个方格提供一个圆角矩形背景。如果您想要自定义此布局,请随意更改。 步骤3:创建背景样式 在res/drawable文件夹中创建一个名为tile_background.xml的新XML文件,并添加以下代码: ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="8dp" /> <solid android:color="@color/tile_background_color" /> </shape> ``` 这个文件定义了一个圆角矩形的背景,用于所有游戏方格。 步骤4:创建游戏逻辑 我们需要编写一些Java代码来处理游戏逻辑,包括移动方块、合并数字等。在Java文件夹中创建一个名为GameBoard.java的新类,并添加以下代码: ``` public class GameBoard { private int[][] board; public GameBoard() { board = new int[4][4]; // Initialize board with two random tiles addRandomTile(); addRandomTile(); } public void addRandomTile() { Random rand = new Random(); int value = rand.nextInt(2) == 0 ? 2 : 4; int row = rand.nextInt(4); int col = rand.nextInt(4); if (board[row][col] == 0) { board[row][col] = value; } else { addRandomTile(); } } public void moveLeft() { boolean moved = false; for (int row = 0; row < 4; row++) { for (int col = 0; col < 3; col++) { if (board[row][col] == 0) { // Skip empty tile continue; } for (int k = col + 1; k < 4; k++) { if (board[row][k] == 0) { // Move tile to empty space board[row][k] = board[row][col]; board[row][col] = 0; moved = true; } else if (board[row][k] == board[row][col]) { // Merge tiles board[row][k] *= 2; board[row][col] = 0; moved = true; break; } else { // Stop searching for mergeable tile break; } } } } if (moved) { addRandomTile(); } } // Add moveRight, moveUp, and moveDown methods here public boolean isGameOver() { // Check if board is full for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { if (board[row][col] == 0) { return false; } } } // Check if any adjacent tiles can be merged for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { if (row < 3 && board[row][col] == board[row+1][col]) { return false; } if (col < 3 && board[row][col] == board[row][col+1]) { return false; } } } return true; } public int getValue(int row, int col) { return board[row][col]; } } ``` 这个类包含一个二维数组来表示游戏板。我们还有几个方法来添加新块、将块移动到不同的位置、检查游戏是否结束以及获取每个块的值。请注意,我们只实现了向左移动的逻辑,需要添加向右、向上和向下的移动逻辑。这些方法需要在后面添加。 步骤5:创建游戏活动 我们需要创建一个包含游戏逻辑和用户界面的活动。在Java文件夹中创建一个名为GameActivity.java的新类,并添加以下代码: ``` public class GameActivity extends AppCompatActivity { private GameBoard gameBoard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); gameBoard = new GameBoard(); updateBoard(); } private void updateBoard() { GridLayout grid = findViewById(R.id.game_board); for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { TextView tile = (TextView) grid.getChildAt(row*4 + col); int value = gameBoard.getValue(row, col); if (value == 0) { tile.setText(""); } else { tile.setText(Integer.toString(value)); } } } } public void onLeftClick(View view) { gameBoard.moveLeft(); updateBoard(); if (gameBoard.isGameOver()) { // Show game over dialog } } // Add onRightClick, onUpClick, and onDownClick methods here } ``` 这个类包含一个GameBoard对象,以及一个updateBoard方法来更新游戏界面。我们还添加了四个onClick方法,每个方法对应于一个方向的移动。这些方法需要在后面添加。 步骤6:链接布局和活动 现在我们需要将游戏布局和活动链接起来。在activity_game.xml布局文件中添加以下代码: ``` <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/move_left" android:onClick="onLeftClick"/> <!-- Add three more buttons here --> <include layout="@layout/game_board"/> ``` 这个文件包含四个按钮,每个按钮对应于一种移动方向。我们还使用include标记包含了游戏布局。现在,当用户单击任何一个按钮时,它将调用对应的onClick方法。 步骤7:测试游戏 现在您已经完成了2048游戏的制作,可以运行它来测试。如果一切正常,您应该能够看到一个包含16个方格的游戏界面,并且可以使用四个按钮来移动方块。 总结 这是一个简单的2048游戏制作教程,仅用于演示如何使用Android Studio和Java来创建游戏。您可以自由地扩展代码以添加更多功能,例如计分、动画效果和音效。希望这个教程对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值