简体   繁体   中英

GridLayout covering more than the screen size

Hello i am trying to make a design of chess board, I am using GridLayout containing buttons that corresponds to blocks of the boards. But the layout is so much bigger that it is not fitting the screen, how can i reduce the button size so that the layout fits the screen.

here is the code

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++;
            }
        }
    }
}

and below is the xml file

<?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>

and the screenshot of the problem is below 在此处输入图片说明

Please help, sorry for mistakes and thanks for help.

In your code you have created Buttons programmatically and you haven't specified any width or height for them. You can add the below line in your code and the width and height will be adjusted.

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

But for implementing a chess game, I you should better create a custom adapter for the gridview and images for black and white boxes should be inflated. Anyway for your current try this would help you.

Note: The width and height are just a random number currently given as 100.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM