0

I have a view that is the same size as my screen / fragment. However, I want to add a padding on the left and right edges such that on all devices, this padding looks like its the same size. when I use:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingStart="20dp"
    android:paddingEnd="20dp">
....

The padding is not equal on all devices. On a tablet, it is much smaller than on a small phone. Is there a way maybe programmatically to set the padding as equal on all devices?

and is dp supposed to be density-independent? Then how come, on different density devices the padding set to dp is not always the same size visually?

bcsta
  • 1,963
  • 3
  • 22
  • 61

3 Answers3

1

Notice that what you want is not scalable and not recommended. The reason is that the sizes of devices vary a lot in Android, as well as their pixel densities.

Furthermore, I include a more general article that might help you.

However:

A. Try with other units like mm or in, which are "based on the physical size of the screen" (see documentation).

B. Maybe set it programmatically. That is, calculate how many px/etc. you need on each device so that it looks the same (mm) on all of them.

float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1, getResources().getDisplayMetrics());

Finally, I am not sure if this is the case, but as other users sugest, maybe this could help. Once again, however, I am not entirely sure if this is what you need. On the same line, you can also define sizes depending on the details of the device with qualificators (refer here).

miquelvir
  • 1,748
  • 1
  • 7
  • 21
0

You need manage different dimens file for different resolutions , please check this link , You just need to put your padings parameter in dimens and then use from dimens.

How to define dimens.xml for every different screen size in android?

Avinash tiwari
  • 269
  • 1
  • 11
-1

Like the answer said in here

on API 21 padding doesn't work via XML, you can define programmatically like the link i share above

but you can try create style="@style/RootLayoutWithPadding" use this in your view

and inside styles.xml add this

<style name="RootLayoutWithPadding"> <item name="android:paddingLeft">@dimen/activity_horizontal_margin</item> <item name="android:paddingTop">@dimen/activity_vertical_margin</item> <item name="android:paddingRight">@dimen/activity_horizontal_margin</item> <item name="android:paddingBottom">@dimen/activity_vertical_margin</item> </style> for every padding you can fill the sizes you want inside values.xml

i hope it help you :)