How an Edit Text can be created dynamically in Android

android

Solution

setContentView(R.layout.main);
        LinearLayout ll = (LinearLayout)findViewById(R.id.ll);
        Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int width = display.getWidth()/3;
        for(int i=0;i<2;i++){
            LinearLayout l = new LinearLayout(this);
            l.setOrientation(LinearLayout.HORIZONTAL);
            for(int j=0;j<3;j++){
                EditText et = new EditText(this);
                LayoutParams lp = new LayoutParams(width,LayoutParams.WRAP_CONTENT);
                l.addView(et,lp);
          }
            ll.addView(l);
        }

use the above code in your onCreate() where "main" is xml file. and you can replace i<2 and j<3 with values of edittext 1 & 2.

sample main.xml which i am using is below::

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <EditText
        android:id="@+id/et1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>


    <EditText
        android:id="@+id/et2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />


    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

Problem

I am new to android programming and I have a problem of creating text fields dynamically; I want to create a view in which there is a button named "Create text fields" and two Edit Text one Edit Text name is ROW and the second edit text name is COLUMN. As a user enters numbers in the both Edit Text let say ROW =2 and COLUMN =3 and press the button "Create text fields" it may create 6 Edit Text below the button of "Create text fields". These 6-edit text should be positioned in 2 rows and 3 columns like below EditText-1 EditText-2 EditText-3 EditText-1 EditText-2 EditText-3

Original source