Rohit Malish
Rohit Malish

Reputation: 3229

Adding EditText to LinearLayout programmatically in Android

I can't make my EditTexts to fit in LinearLayout side by side sharing the same amout of space.

Here is the code that does it:

LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

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

        textFieldsLayout = (LinearLayout) findViewById(R.id.LinearLayout2);

        for(int i=1; i <= 8; i++){

            final EditText ed = new EditText(this);

            ed.setText("" + i);

            ed.setInputType(2);

            ed.setLayoutParams(lparams);

            textFieldsLayout.addView(ed);
        }   
    }

this code manages to add EditText to my layout but they appear side by side, and there is empty space at the end of LinearLayout, when I change params to WRAP_CONTENT, only first EditText added to layout fills the layout and others don't appear there, any idea what am I doing wrong here?

Upvotes: 2

Views: 4448

Answers (2)

RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

add layout_weight to the layout params

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                       (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);

Upvotes: 2

Frank Sposaro
Frank Sposaro

Reputation: 8531

To make your views stretch to fill a LinearLayout you must make sure that the widths are set to 0 and the weights are set to 1.

This will give them an even split. It's basically telling the system to defer setting the width until its parent is measured. Then come up and let children fill in whatever space they have.

Upvotes: 0

Related Questions