How to Add 3 Elements in a LinearLayout and Let the Central One Occupy Max Width (Android app)
Posted: May 5th, 2015 | Author: Julia | Filed under: Mobile Design and Development, Tips and Tricks | Tags: Android, linear layout, LinearLayout, mobile, Xamarin | No Comments »Once working on the implementation of Calendar app design for Android I got a problem: I need to put 3 elements (right button, month title, left button) in an android layout.
The requirements were:
1. They should all be in one row.
2. The central part (month) should fill all space of the display width (except part where buttons are located).
It seems to be easy at the very first sight.. in fact all my elements were stuck to the left or buttons wouldn’t move to the right and left side..
The final solution was to use a LinearLayout and set for each element the attribute android:layout_weight=”1″, which will make them all equal weights and take up the space, and the attribute android:layout_width=”fill_parent” for my central control:
-
<LinearLayout
-
android:id="@+id/Text"
-
android:orientation="horizontal"
-
android:layout_width="fill_parent"
-
android:layout_height="50dip"
-
android:layout_centerHorizontal="true"
-
android:clickable="false">
-
<calendarcontrol.android.controls.FontAwesomeIcon
-
android:text="\uf053"
-
android:layout_width="60dip"
-
android:layout_height="20dip"
-
android:textSize="20dip"
-
android:clickable="true"
-
android:gravity="left"
-
android:layout_weight="1" />
-
<calendarcontrol.android.controls.TitleView
-
android:id="@+id/DateLabel"
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:textColor="#000"
-
android:textSize="20dip"
-
android:gravity="center_horizontal"
-
android:layout_weight="1" />
-
<calendarcontrol.android.controls.FontAwesomeIcon
-
android:text="\uf054"
-
android:layout_width="60dip"
-
android:layout_height="20dip"
-
android:textSize="20dip"
-
android:clickable="true"
-
android:gravity="right"
-
android:layout_weight="1" />
-
</LinearLayout>
Note:
1. Weights are for LinearLayouts only. They are specify how much of the extra space in the layout to be allocated to the View. LinearLayout supports assigning a weight to individual children and allows it to expand to fill any remaining space in the parent view. Views’ default weight is zero.
The formula to count is
Space assigned to child = Child’s individual weight / Sum of weight of every child
2. You can use instead of my custom ‘calendarcontrol.android.controls.FontAwesomeIcon’ control Button, TextView or what you do need.
Leave a Reply