0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

oh, how did I forget that! Thank you!
you're welcome, please consider upvoting and accepting if it helped. also if you have any doubts feel free to ask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.