3

I'm trying to create a form which can add additional fields when the user clicks a button ie A LinearLayout which contains a TextView and 2 EditText. Similar to a Contacts app. Can anyone recommend a tutorial or example?

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Jey Atiwat
  • 63
  • 1
  • 5

2 Answers2

2

Create a linear layout that will contain dynamic views you want, create a layout file you want to add dynamically, make a class for inflating that layout to your activity and use its object to get the view and add it to that box(layout in which you want dynamic views). You can go like this.

public class BoxView {
    private Context context;
    private TextView tv;
    private EditText edt;
    private Button btn;
    private View v;

    public BoxView(Context context) {

        // TODO Auto-generated constructor stub
        this.context= context;
        init();
    }

    private void init() {
        // TODO Auto-generated method stub
        LayoutInflater inflator= LayoutInflater.from(context);
         this.v= inflator.inflate(R.layout.sample_layout, null);

        this.tv=(TextView)v.findViewById(R.id.textView1);
        this.edt=(EditText)v.findViewById(R.id.editText1);
        this.btn=(Button)v.findViewById(R.id.button1);

    }

    public View getView(){
        return v;
    }
    public void setTv(TextView tv) {
        this.tv = tv;
    }
    public TextView getTv() {
        return tv;
    }
    public void setEdt(EditText edt) {
        this.edt = edt;
    }
    public EditText getEdt() {
        return edt;
    }
    public void setBtn(Button btn) {
        this.btn = btn;
    }
    public Button getBtn() {
        return btn;
    }


}

and in your activity you can do like this:

 LinearLayout layout=(LinearLayout)findviewbyId(R.id.layout1);
 BoxView box=new BoxView(context);
 layout.addView(box.getView);
mayank_droid
  • 1,015
  • 10
  • 19
2

You can add new Component by adding them to parent layout define in xml (you can refer that layout by giving id to it and access it in your activity by using LinearLayout linearLayout = findViewById(R.id.idOfLayout); in this LinearLayout you get that parent layout and you can add another layouts to it by dynamically creating them)

Here are some links that helps you to understand dynamically ading and removing components in Android

Build dynamic form through code Link.. LinearLayout adding removing ElementsLink..

Community
  • 1
  • 1
MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36