TextView.setWidth not working if no text

420 views Asked by At

I am dynamically adding TextViews to a LinearLayout, setting their layout parameters appropriately. The LinearLayout is inside a custom scrollview.

I don't have the text for each TextView immediately, so some of them get set at different times, and some of them never get set. I'd like them all to be the same width, so I have to wait until onLayout to update their width (each textview should be 1/2 the width of the scrollview).

My problem: Only the TextViews with text are appearing. If text is null or empty, they just don't display, even though I am setting their width in onLayout.

Add the TextViews:

//This happens when scrollView is created. We don't have the scrollview's width yet
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);

/**add layout rules omitted **/

linearLayout.addView(textView);

Then set their width:

@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);

    int width = getWidth();
    int totalWidth = 0;
    for (int i = 0; i < linearLayout.getChildCount(); i++) {
        TextView textView = linearLayout.getChildAt(i);
        //Each textView will be 1/2 the width of the scrollview
        textView.getLayoutParams().width = width / 2;//Try setting params width
        textView.setWidth(width / 2);//Try directly setting width
        totalWidth += width / 2;
    }
    linearLayout.getLayoutParams().width = totalWidth;
    linearLayout.setMinimumWidth(totalWidth);
    linearLayout.requestLayout();

Note I tried setting their width 2 different ways above, but nothing works. Do TextViews not have a width if they have no text?

1

There are 1 answers

5
xyz On

You need to resize the LinearLayout before the child TextViews.

Calculate the total width first, apply it to the parent Layout, then apply half widths to each TextView.

I don't see currentWidth either, so I am not adding complete code myself.

EDIT:

linearLayout.getLayoutParams().width = totalWidth = width * 0.5 * linearLayout.getChildCount();
linearLayout.setMinimumWidth(totalWidth);

for (int i = 0; i < linearLayout.getChildCount(); i++) {
    TextView textView = linearLayout.getChildAt(i);
    textView.setText(""); // I don't think this is needed, but you CAN add this too
    //Each textView will be 1/2 the width of the scrollview
    textView.getLayoutParams().width = width / 2;//Try setting params width
    textView.setWidth(width / 2);//Try directly setting width
}


linearLayout.requestLayout();