Android Gridlayout Example Programmatically

android.widget.GridLayout is a layout manager used to arrange child views in a grid. You can specify how many columns and rows the grid have with it’s rowCount or columnCount property. You can change the GridLayout object size by specifying it’s layout_margin property. You can even use it’s child view’s layout_rowSpan or layout_columnSpan property to merge nearby rows or columns.

1. GridLayout Example.

  1. The GridLayout object in this example has two columns. The first row is a user name row, the user can input the user name in the input text box. The second row is a password row, the user input a password in it.
  2. The third row contains only one button, the button merges two columns by setting it’s layout_columnSpan property. When this button is clicked, it will add a new password row in the GridLayout object programmatically.
    android-gridlayout-after-add-two-pasword-row

2. Design UI With GridLayout Statically

  1. Create a new android project with empty activity template, name it as Android GridLayout Example. Then double click app/res/layout/activity_main.xml file to open it in UI designer.
  2. Drag and drop GridLayout from the designer’s Pallete to the Component tree and set it’s attribute values in the right Attributes panel. Then drag and drop TextView, EditText, and Button under the GridLayout component and set related attributes.
  3. After the design, click the Text tab at the bottom, and change the related attribute’s value like below.
  4. activity_main.xml
    <GridLayout
        android:id="@+id/grid_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnCount="2"
        android:layout_margin="80dp">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User Name:" />
    
        <EditText
            android:id="@+id/textview_user_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Input user name " />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password:" />
    
        <EditText
            android:id="@+id/edittext_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword" />
    
        <Button
            android:id="@+id/button_add_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add Password"
            android:layout_columnSpan="2"
            android:textAllCaps="false"/>
    
        <Button
            android:id="@+id/button_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login"
            android:layout_columnSpan="2"
            android:textAllCaps="false"/>
    
    </GridLayout>
    
    

3. Add Child View To GridLayout Programmatically.

  1. Now when clicking Add Password button, it will add a row ( a text view as password label and a password input text box ) in the GridLayout. This function is implemented in activity java code. Please see the below code comments for detail.
  2. MainActivity.java
    package com.dev2qa.android.example.androidgridlayoutexample;
    
    import android.content.Context;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.text.InputType;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.GridLayout;
    import android.widget.TextView;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Get the GridLayout layout object.
            final GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout);
    
            // Get add new password button.
            Button addPasswordButton = (Button)findViewById(R.id.button_add_password);
    
            // When the button is clicked.
            addPasswordButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Used to save exist password element count.
                    int existPasswordRowNumber = 0;
    
                    // Get all GridLayout child count.
                    int childCount = gridLayout.getChildCount();
    
                    // Loop all the GridLayout child.
                    for(int i=0;i<childCount;i++)
                    {
                        // If one child is EditText type.
                        Object child = gridLayout.getChildAt(i);
                        if(child instanceof EditText)
                        {
                            // Get it's input type.
                            EditText editText = (EditText)child;
                            int inputType = editText.getInputType();
    
                            // If the edit text input type is password. The real value is 129 which is InputType.TYPE_TEXT_VARIATION_PASSWORD + 1.
                            if(inputType == InputType.TYPE_TEXT_VARIATION_PASSWORD + 1)
                            {
                                // Exist password row number plus 1.
                                existPasswordRowNumber++;
                            }
                        }
                    }
    
                    // Get application context.
                    Context context = getApplicationContext();
    
                    // Create a text view component.
                    TextView passwordTextView = new TextView(context);
                    // Set password label text value.
                    passwordTextView.setText("Password " + existPasswordRowNumber + ":");
    
                    // Create a edit text component.
                    EditText passwordEditText = new EditText(context);
                    // Set edit text input type to password.
                    passwordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD + 1);
                    // Set edit text size to 10 ems.
                    passwordEditText.setEms(10);
    
                    // Insert password label at last third position.
                    gridLayout.addView(passwordTextView, childCount - 2);
    
                    // Recalculate gridlayout child count again.
                    childCount = gridLayout.getChildCount();
                    // Insert password input box at last third position again.
                    gridLayout.addView(passwordEditText, childCount - 2);
    
                }
            });
    
        }
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Jerin
Jerin

Can i get some help.I on a project on a calendar.How can i enter numbers in a grid layout pro grammatically on android.

SADAT
SADAT

You have made my app look extremely wonderful

2
0
Would love your thoughts, please comment.x
()
x