How to set width to textview in one child exactly the same as the textview in another child?

130 views Asked by At

I make some custom view, and now im stuck with one specific issue. Now ill try to explain: in my case the view hierarchy is

<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>

the child items are added according to the data coming from the server. I want to make all textviews with the same width - width of textview which content length is max. How can I implement this? I tried to calculate width in onMeasure callback, and then set width to another views, but getMeasuredWidth() and getWidth() returns 0 every time. I Heard something about ViewTreeObserver, but i can not understand how to use it right. Thanks in advance!

1

There are 1 answers

0
Shubham Vala On

Try this,

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

same code for tv2,tv3 and tv4. it will work.