All we need is an easy explanation of the problem, so here it is.
this is my code and its output:
<?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">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="0dp"
app:layout_constraintWidth_percent="0.5"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.5"
android:layout_marginStart="68dp"
android:layout_marginTop="96dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
now viewpager width is 50% of device width and viewpager height is 50% of device height but I want to set viewpager height base on device width (50% of device width), is it possible?
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
You can use ratio constraint attribute of the ConstraintLayout :
Add this line in the layout to have height equal to width :
app:layout_constraintDimensionRatio="1:1"
And Remove this line :
app:layout_constraintHeight_percent="0.5" //remove this
This will form a perfect square view with equal width and height.
Have a look : ConstraintLayout | Ratio
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0