2

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?

2
  • Post a screenshot of how your code aligns them in the view, and then we can figure out a way to help you better. Commented Aug 1, 2012 at 17:14
  • i got it already, but the last one added gets streched a little bit more than previous Commented Aug 1, 2012 at 17:25

2 Answers 2

2

add layout_weight to the layout params

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                       (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
Sign up to request clarification or add additional context in comments.

2 Comments

do you know why last ones are getting more space than first ones?
just realised that last ones take more space because of wider numbers in them. thanks!
0

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.

1 Comment

i tried setting widths to 0 and then add 1f to my params, but that only makes my edittexts very thin

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.