I am building an android application and I have a dialog fragment. The dialog fragment has a set width. However, the issue is that when the app is run on a device with a different screen size, the dialog fragment isn't centered properly.
Initially, what I had was:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="500dp"
android:layout_height="wrap_content">
<-- code goes here -->
</RelativeLayout>
As you can see, I have a relativeLayout with a defined width. Since I know that you can't use layout_weight
in a relative layout, what I did was I wrapped that parent relative layout in a linear layout as such:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:weightSum="1">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</RelativeLayout>
</LinearLayout>
However, that doesn't work since the dialog fragment is cut when I run the application on a device with smaller screen size.
How can I set the width a dialog fragment as a percentage of the screen size? Is this possible at all or would I have to resort to setting it programmatically?
This is a correct way, if you want RelativeLayout have 40% width of the screen, but this technique cant apply to the parent layout, because parent layout doesn't have parent layout and android:layout_weight doesn't affect
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="40">
</RelativeLayout>
Since I know that you can't use layout_weight in a relative layout
We can use layout_weight in any view and layout, if it direct child of a LinearLayout