Search code examples
javaandroidviewandroid-gridlayout

How to Divide screen into 4 equal part using Grid layout in android?


I have try to divide the screen into 4 equal parts but got problem.

   <GridLayout
       android:rowCount="2"
       android:columnCount="2"
       android:layout_width="match_parent"
       android:layout_height="match_parent">


       <View
           android:background="@drawable/rectangle"
           android:layout_column="0"
           android:layout_row="0"
           />


       <View
           android:background="@drawable/rectangle"
           android:layout_column="1"
           android:layout_row="0"
           />

       <View
           android:background="@drawable/rectangle"
           android:layout_column="0"
           android:layout_row="1"
           />

          <View
           android:background="@drawable/rectangle"
           android:layout_column="1"
           android:layout_row="1"
           />

and the the rectangle.xml file is

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="20dp" />
    <solid android:color="#ffffffff" />
</shape>

Right now rectangle are going outside of screen and first column filling the whole screen.


Solution

  • Starting API 21 you can use weights in GridLayout:

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="2"
            android:rowCount="2">
    
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:background="@drawable/rectangle"/>
    
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:background="@drawable/rectangle"/>
    
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:background="@drawable/rectangle" />
    
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:background="@drawable/rectangle" />
    
    </GridLayout>
    

    Use android.support.v7.widget.GridLayout if you need to support previous apis