AndroidDev
AndroidDev

Reputation: 16375

Adjusting the Width of a LinearLayout Children

I have a Layout to which i dynamically add rows to. Each row consists of a TextView and an EditText. Now the texts for the EditText are set at runtime, so i want them all to be neatly alligned like a inout form where a textfield is at the left and an edittext on the right.

This my code

for (int i = 0; i < itemsContainer.getChildCount(); i++) 
    {
        View v=itemsContainer.getChildAt(i);
        if(v instanceof ClickableButtonView)
        {
            TextView textView=((ClickableButtonView)v).getItem();
            if(textView.getWidth() > width)
            {
                width=textView.getWidth();
            }
        }

    }

    for (int i = 0; i < itemsContainer.getChildCount(); i++) 
    {
        View v=itemsContainer.getChildAt(i);
        if(v instanceof ClickableButtonView)
        {
            TextView textView=((ClickableButtonView)v).getItem();
            textView.setLayoutParams(new LayoutParams(width, LayoutParams.WRAP_CONTENT));
        }

    }

Now what happens is that my layout, with the textview collapses, and only the element on the right side takes up the complete space. I want to iterate over the LineraLyout, find the edittext that is taking the most room and set the all the edittext to take up the exact same room. Can this be done ?

Upvotes: 0

Views: 383

Answers (1)

Mal
Mal

Reputation: 373

Call this method in a loop to set the style for your textviews with any weights required. Giving weight 1 to all will make it equal.

private void setStyle(TextView textView, float weight) {
    textView.setSingleLine(false);
    textView.setWidth(0);
    textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, weight));
    textView.setPadding(8, 0, 8, 0);
    textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
}

Upvotes: 1

Related Questions