I have a layout like below. Now, I don't want to set the width of relative layout to fixed 240 dp. I want to set the width of the relative layout to 1/3 the width of the screen. Is it possible to do that in the xml file. If it is impossible, how can I achieve that using java code ?
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/fullscreen"
style="@style/translucent">
<RelativeLayout
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:gravity="center"
android:background="#88000000"
android:id="@+id/sidebar">
</RelativeLayout>
</FrameLayout>
RelativeLayout is a view group that displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center).
Android Positioning Views in Relative Layout As we discussed, in RelativeLayout we need to specify the position of child views relative to each other or relative to the parent. In case if we didn't specify the position of child views, by default all child views are positioned to top-left of the layout.
We can use LinearLayout inside RelativeLayout. We can also use RelativeLayout as a Child of LinearLayout.
use weightsum="3"
in the parent and layout_weight=1
in the child. Take a look a this reference
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/fullscreen"
style="@style/translucent"
android:orientation="horizontal"
android:weightSum="3">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:gravity="center"
android:background="#88000000"
android:id="@+id/sidebar"
android:layout_weight="1"
>
</RelativeLayout>
<!-- other views, with a total layout_weight of 2 -->
</LinearLayout>
You have to use a LinearLayout
to get the width of a view to be a third of its parentview.
Something like:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:background="#88000000">
</RelativeLayout>
<ViewGroup
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2">
</ViewGroup>
</LinearLayout>
The key bit is the ratio of the layout_weights. The documentation is pretty good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With