Android Gridlayout Example Programmatically

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

1. GridLayout Example.

android gridlayout exampleandroid gridlayout after add two pasword row

The gridlayout in this example has two columns. The first row is a user name row, user can input user name in the input text box. The second row is a password row, user input password in it.

The third row contains only one button, the button merger two columns by setting it’s layout_columnSpan property. When this button is clicked, it will add a new password row in the gridlayout programatically.

2. Design UI With GridLayout Statically

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.

Drag and drop GridLayout from designer’s Pallete to Component tree and set it’s attributes values in right Attributes panel. Then drag and drop textview, edittext and button under the gridlayout component and set related attributes.

design gridlayout example ui with designer

After design, click Text tab at bottom, change related attribute’s value like below.

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>

2. Add Child View To GridLayout Programmatically.

Now when click 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 code comments for detail.

READ :   Android ToggleButton Example

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

            }
        });

    }
}
(Visited 3,909 times, 26 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

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