0

I have a layout with some Views that I need to change size depending on some parameters, that depend on width of the View. The width is set to "match_parent". So when I try to get the width it returns 0. Here is what I have tried so far:

  1. mask.getWidth();
  2. mask.getLayoutParams().width
  3. ViewTreeObserver vto = mask.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mask.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = mask.getMeasuredWidth(); } });

So my question is how do I get the width in this situation? Thank you.

Sermilion
  • 1,920
  • 3
  • 35
  • 54

1 Answers1

1

After digging around I found a solution that answers my question but has a major problem that I am yet to resolve. We can use method post() that every View has and adds a Runnable to the message queue. So as I understand what happens is after View is fully measured in method post() we can get dimensions that we need like this:

 holder.button.post(new Runnable() {
                @Override
                public void run() {
                    width = holder.button.getWidth();
                }
            });

However the problem here is that RecyclerView won't wait until this view is measured as and will go to next row and rows won't be updated according to measures that you expect. If anyway has a way to go about this problem please leave a comment. Thank you.

Sermilion
  • 1,920
  • 3
  • 35
  • 54