0

I have to set an image in my activity and in my scenario the image covers fairly large portion of the activity. However I want to keep its width/height to be no more than 33% of its parent viewGroup's width.

I am dynamically changing the ImageView's dimension at runtime using this code.

     @Override
protected void onResume() {

    super.onResume();       

    //try to resize the imageview according to current width of container layout
    int nWidthPix = findViewById(R.id.layout_info).getWidth();      
    ImageView imView = (ImageView)findViewById(R.id.imageView_main);
    imView.setAdjustViewBounds(true);
    int imViewWidth = nWidthPix/3;
    imView.setMaxWidth(imViewWidth);
    imView.setMaxHeight(imViewWidth);
    //
    }

The problem is that nWidthPix which is width of RelativeLayout which contains my ImageView is returned 0 in the first call to onResume() that is when the app is launched for first time. As a result image is not shown , in the subsequent calls to onResume() it returns 720 which is correct.

I am guessing that since the view is not really shown yet before the first call on onResume it does not know the width ? but then we can find views on the other hand even before the activity is shown for the first time. .. Not sure what's causing it.

Help

Ahmed
  • 14,503
  • 22
  • 92
  • 150
  • What happens when you add setContentView(R.layout.YOUR_LAYOUTNAME); after super.onResume(); ? – bpavlov Jun 01 '14 at 00:17
  • setContView is done in the onCreate which is called before onResume() not after onResume() – Ahmed Jun 01 '14 at 00:22

2 Answers2

1

You can use the ViewTreeObserver of the root layout and set an OnGlobalLayoutListener to know when the layout finishes loading. Take a look at this answer for a reference.

Community
  • 1
  • 1
Emmanuel
  • 13,083
  • 4
  • 39
  • 53
0

View always report 0 as their width and height before they've been measured by the framework. onResume() is too soon to query this information, unfortunately.

If the parent view is the Activity itself, then you can get the window's dimensions (for example with this method) and use those values. Otherwise you need to postpone execution of this code until the layout pass is complete (via an OnGlobalLayoutListener).

Community
  • 1
  • 1
matiash
  • 54,791
  • 16
  • 125
  • 154