GridLayout 覆盖超过屏幕尺寸

GridLayout covering more than the screen size

你好,我正在尝试设计棋盘,我正在使用包含与棋盘块对应的按钮的 GridLayout。但是布局太大了,不适合屏幕,我怎样才能减小按钮大小,使布局适合屏幕。

这是代码

public class BoardActivity extends AppCompatActivity {

    private GridLayout mBoard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_board);

        mBoard = (GridLayout)findViewById(R.id.board_grid);
        addItems();
    }

    public void addItems(){
        int index = 0;
        Button button;
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                button = new Button(this);
                button.setId(index);
                button.setPadding(0,0,0,0);
                button.setText(""+index);
                mBoard.addView(button);
                index++;
            }
        }
    }
}

下面是 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"

    android:layout_height="match_parent"
    tools:context="com.example.harsh.chessgame.BoardActivity">

    <GridLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:rowCount="8"
        android:columnCount="8"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="0dp"

        android:id="@+id/board_grid">

    </GridLayout>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/test_text"/>
</LinearLayout>

问题截图如下

请帮忙,对错误表示抱歉,感谢您的帮助。

在您的代码中,您以编程方式创建了按钮,但没有为它们指定任何宽度或高度。您可以在您的代码中添加以下行,宽度和高度将被调整。

button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));

但是为了实现国际象棋游戏,我最好为 gridview 创建一个自定义适配器,并且黑白框的图像应该被放大。无论如何,对于您当前的尝试,这会对您有所帮助。

注意:宽度和高度只是随机数,目前为 100。