I have a custom layout with width="match_parent"
. Layout consists of big circle in the center and smaller one just next to it.
On my screen I have found the dimensions that I like and now I want to make it look similar across all devices.
My device is Galaxy S8 with display metrics reported as:
DisplayMetrics {
density=3.5,
width=1440,
height=2960,
scaledDensity=2.8,
xdpi=562.707,
ydpi=565.293
}
So as I understand I have 411dp in width available.
For dimensions I have
Now I wonder how should I go with this. I have 2 options in my mind. First will be to create separate values for other screen densities, or just convert this dimensions into percentage and do the layout programmatically.
My problem with first option is that some devices (like mine) have screen zoom which changes scaledDensity
making it look totally different.
You can support different screen sizes use ConstraintLayout:
ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It's similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it's more flexible than RelativeLayout and easier to use with Android Studio's Layout Editor.
You can use those attributes to specify your views size in precents:
app:layout_constraintWidth_percent=".5"
app:layout_constraintHeight_percent=".5"
For example, single button that is equal to 50% of the screen both in height and width:
<?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">
<Button
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".5"
app:layout_constraintHeight_percent=".5"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And it will look something like this:
One more thing, because different phones got different screen size you better not use fixed size dimensions (50dp
for example )on your views.
I can recommend using ConstraintLayout with guidelines and Chains to support different screen sizes (In addition to what I mentioned above - app:layout_constraintWidth_percent
and app:layout_constraintHeight_percent
).