why doesn't onSizeChanged return View's correct dimensions?

Viewed 151

I'm building a custom view. When inserting custom view to xml, i'm setting it as a single child and sets it's layout_width and layout_height to match_parent.

When printing its height and width in onSizeChange method, i don't get the width and height screen size, just dimensions that i can't understand how they where calculated.

I'm running the app on Samsung Galaxy S8 device.

Xml:


    <?xml version="1.0" encoding="utf-8"?>
   <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".MainActivity">
   
   
   <com.example.ptacticedrawimg.Rectangle
       android:layout_width= "match_parent"
       android:layout_height="match_parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent"/>
   
   </androidx.constraintlayout.widget.ConstraintLayout>

Custom View Code:

    public class Rectangle extends View {
        public Rectangle(Context context) {
            super(context);
            Log.e("Rectangle Constructor1","runs");
        }
    
        public Rectangle(Context context, AttributeSet attr)
        {
            super(context,attr);
            Log.e("Rectangle Constructor2","runs");
        }
    
        public Rectangle(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            Log.e("Rectangle Constructor3","runs");
        }
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            Log.e("onSizeChanged","oldh = " + oldh + " oldh = " +oldh +   "h = " + h + " w = " + w);
    
        }
    
    
        @Override
        protected void onDraw(Canvas canvas) {
            Log.e("1234",""+ getMeasuredWidth());
            super.onDraw(canvas);
            LinearGradient linearGradient = new LinearGradient(200, 200, 600, 600, Color.GREEN, Color.YELLOW, Shader.TileMode.REPEAT);
            Paint mPaint = new Paint();
            mPaint.setShader(linearGradient);
            canvas.drawRect(200, 200, 600, 600, mPaint);
        }

Log Output:

2020-07-23 14:27:10.034 9633-9633/com.example.ptacticedrawimg E/Rectangle Constructor2: runs
2020-07-23 14:27:17.250 9633-9633/com.example.ptacticedrawimg E/onSizeChanged: oldh = 0 oldh = 0h = 1836 w = 1080
2020-07-23 14:27:17.295 9633-9633/com.example.ptacticedrawimg E/1234: 1080
0 Answers
Related