Search code examples
androidandroid-layoutandroid-imageview

How to ensure correct/direct dimension scaling on android in layouts and elsewhere?


Is there any unit that I can use that would scale directly? Is the only way really to write everything in px and multiply it by correct scale ?

(scale = <real screen height>/<template base height> . and every dimension is <dimen in px> * scale)

"dp" with the bucket approach does not work for me - I'm writing for small screens where the element is long off the screen before the next dp scaling threshold is triggered.

Currently my workaround for drawing on canvas is (below) but I dont know how to reconcile it with using xml layouts

@Override
    public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        super.onSurfaceChanged(holder, format, width, height);
        screenScale = ((float) width) / (float) mBackgroundBitmap.getWidth();
        mTopBarYOffset = mTopBarYOffset * screenScale;
        mTopBarXOffset = mTopBarXOffset * screenScale;
//and so on for every dimension

Solution

  • You can use ConstraintLayout.

    In ConstraintLayout you can work with percent like this:

     <Button
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.6" //line 1
        app:layout_constraintWidth_percent="0.5"  //line 2 
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    

    So what I did - I told my button to be equal to 60% of its parent in height (see line 1) and also I told my button to be equal to 50% of its parent Width(see line 2).

    For more complex layouts I would also use guidelines and Chains to make it easier to make a responsive layout.