Pauline Hicks
Pauline Hicks

Reputation: 11

Adding Layout with views programmatically

Pretty much I have 1 main layout being a Vertical LinearLayout, at the press of a button I want to be able to add a horizontal layout with 2 edit texts. What i've done here doesn't work, no errors but nothing happens.

public void addView(View v){
    LinearLayout mainLayout =(LinearLayout)findViewById(R.id.activity_main);

    LinearLayout h = new LinearLayout(this);

    h.setOrientation(LinearLayout.HORIZONTAL);
    h.addView(new EditText(this));
    h.addView(new EditText(this));

    mainLayout.addView(h);
}

Upvotes: 0

Views: 30

Answers (1)

lelloman
lelloman

Reputation: 14173

one thing that you should consider when creating a View programmatically is to set a LayoutParams, e.g.

LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WrapContent);
view.setLayoutParams(layoutParams);

this way you define the size of the view inside the layout, it's what you would usually set with layout_width and layout_height attributes in an xml layout

in your case you should add a LayoutParams for the LinearLayout and one for each the EditText

Upvotes: 1

Related Questions