0

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!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • what about setting them all as "match_parent"? – Pier Giorgio Misley Jul 30 '18 at 13:01
  • the child relative layout is looks like <---progressbar--- --textview-->, i have to make all textviews with the same width, not to make them match parent :) – user8983405 Jul 30 '18 at 13:11
  • forgot to tell smth - the orientation of parent layout is vertical – user8983405 Jul 30 '18 at 13:13
  • you can put a fixed width for progressbar and let textview matching the remaining space :) something like this: [margin-left] [progressbar - 200dp width (example)] [textview - matching parent]. Obv aligned to left. this way you will have all progress of same width same as all textviews. you can also use percentagelayout to specify 30% width for progress and 70% for textview – Pier Giorgio Misley Jul 30 '18 at 13:13
  • can you provide a full-example of what you need? using alignments, sizes and orientations in your xml-example? it would be clearer – Pier Giorgio Misley Jul 30 '18 at 13:14

1 Answers1

0

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.

Shubham Vala
  • 1,024
  • 7
  • 18