Search code examples
androidandroid-edittextandroid-linearlayoutlayoutparams

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?


Solution

  • add layout_weight to the layout params

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