Search code examples
javaandroidxmlandroid-studiogrid-layout

What to put in the parameters of the EditText constructor in Android Studio?


I'm still fairly new to Android Studio and I want to test out something by creating a GridLayout with the desired rows and columns and fill it up with EditTexts. However I run into a problem where I do not know what to put as a parameter in the EditText constructor. Here is the java code below:

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

    //The numbers WILL vary but this is just a test
    int rows = 3;
    int columns = 4;

    GridLayout gd = (GridLayout) findViewById(R.id.grid1);
    gd.setRowCount(rows);
    gd.setColumnCount(columns);
    EditText edt;

    for(int r = 0; r < rows; r++)
    {
        for(int c = 0; c < columns; c++)
        {
            //What to put in the parameters in this code below?
            edt = new EditText();
            gd.addView(edt);
        }
    }
}

And here is the XML:   

<GridLayout
        android:id="@+id/grid1"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

</GridLayout>

I looked at the constructor for EditText and find that Context is needed, but how do I put that in there? If this is not the right way to do it, please tell me the right way.


Solution

  • Every Activity is a Context. For Views, you pass in either the Activity you're in, or the parent's Context (via getContext()) depending on what's more convenient. Here generally it would be the Activity, so you pass in this.