【问题标题】:How to set width to textview in one child exactly the same as the textview in another child?如何将一个孩子的 textview 宽度设置为与另一个孩子的 textview 完全相同?
【发布时间】:2019-01-06 17:39:48
【问题描述】:

我制作了一些自定义视图,但现在我遇到了一个特定问题。 现在我试着解释一下:在我的例子中,视图层次结构是

<view extends linear layout>
    <child-view extends relative layout> 
        <some content>
        <relative-layout>
            <progressbar> (align text view right, match parent)
            <textview> (align parent right, wrap content) <- there's i have to make some changes
        <relative-layout>
    <child-view>
    <...>
<view>

根据来自服务器的数据添加子项。 我想让所有文本视图都具有相同的宽度 - 内容长度最大的文本视图的宽度。我该如何实施?我试图在 onMeasure 回调中计算宽度,然后将宽度设置为另一个视图,但 getMeasuredWidth() 和 getWidth() 每次都返回 0。我听说过一些关于 ViewTreeObserver 的事情,但我不明白如何正确使用它。提前致谢!

【问题讨论】:

  • 如何将它们全部设置为“match_parent”?
  • 子相对布局看起来像,我必须使所有文本视图具有相同的宽度,而不是使它们与父视图匹配:)
  • 忘了告诉smth - 父布局的方向是垂直的
  • 你可以为进度条设置一个固定的宽度,让 textview 匹配剩余的空间:) 像这样:[margin-left] [progressbar - 200dp 宽度(示例)] [textview - 匹配父级]。 Obv 左对齐。这样,您将获得与所有文本视图相同宽度的所有进度。您还可以使用 percentlayout 为进度指定 30% 宽度,为 textview 指定 70%
  • 你能提供一个你需要的完整例子吗?在您的 xml 示例中使用对齐方式、大小和方向?会更清楚

标签: android textview android-custom-view android-measure


【解决方案1】:

试试这个,

int maxWidth = 0;

....

tv1.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
@Override 
public void onGlobalLayout() { 
    int width  = layout.getMeasuredWidth();
    if(width > maxWidth){
        maxWidth = width;
        // update all textView width with max width.
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    } else {
        this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    } 
  }
});

tv2tv3tv4 的代码相同。它会起作用的。

【讨论】:

    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2020-11-14
    • 2021-11-09
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多