如果没有文本,TextView.setWidth 不起作用



我正在动态地将TextViews添加到LinearLayout中,并适当地设置它们的布局参数。线性布局位于自定义滚动视图中。

我没有立即为每个 TextView 提供文本,因此其中一些在不同的时间设置,而其中一些永远不会设置。我希望它们都是相同的宽度,所以我必须等到onLayout更新它们的宽度(每个文本视图应该是滚动视图宽度的 1/2)。

我的问题:仅显示带有文本的文本视图。如果文本为 null 或空,即使我以 onLayout 为单位设置它们的宽度,它们也不会显示。

添加文本视图:

//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);

然后设置它们的宽度:

@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();

请注意,我尝试在上面以 2 种不同的方式设置它们的宽度,但没有任何效果。如果文本视图没有文本,它们没有宽度吗?

您需要在子文本视图之前调整 LinearLayout 的大小。

首先计算总宽度,将其应用于父布局,然后将半角应用于每个文本视图。

我也看不到currentWidth,所以我自己没有添加完整的代码。

编辑

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();

最新更新