简体   繁体   中英

How to get width and height of resized custom view , before it is drawn

In my custom View .xml , i have defined width and height as w = 600dp , h = 700dp . Now i know getMeasuredHeight() / getMeasuredWidth() give values of width and height after view is drawn and they may differ from what i've given in .xml file , is there a workaround to get getMeasuredHeight() and getMeasuredWidth() values before view is actually drawn on layout, without use of onMeasure() ?

And How to calculate changed dp sizes in different screens ? like my 600h*700w when run on emulator converts to 300*300 .

You can override onSizeChanged() to get height and width of the view when it is drawn.refer below:

  @Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    mWidth = w;
    mHeight = h;
    super.onSizeChanged(w, h, oldw, oldh);
    Log.d(TAG, "onSizeChanged: " + " width: " + w + " height: " + h + " oldw " + oldw + " oldh " + oldh);
}

To convert dp into pixels you can use following code:

   sizeInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            sizeInDp, getResources().getDisplayMetrics());

I had kind of the same problem.

Here is my solution, how I came across this similar problem. There you can get the Width and Height before the Image is drawn with OnPreDrawListener()

     ImageView iv= binding.photoRoundProfile;
     ViewTreeObserver vto = iv.getViewTreeObserver();
     vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
   
           private int mFinalWidth = 0;
           private int mFinalHeight = 0;
   
           public boolean onPreDraw() {
   
               if(mFinalHeight != 0 || mFinalWidth != 0)
                   return true;
   
               mFinalHeight = iv.getHeight();
               mFinalWidth = iv.getWidth();
               Log.d("hilength","Height: " + mFinalHeight + " Width: " + mFinalWidth);
   
               ImageUtil.setPic(binding.photoRoundProfile, mCurrentPhotoPath);
               return true;
           }
       });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM