Reputation: 3167
I am trying to achieve a layout as follows:
Two views with weight 2(green View) & 1(blue View) in a linear layout. And a floating button centered in between those views infront of them. But it is not possible using linear layout. Can anyone give a little help here
Update: Here is what I have done
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="#22B14C" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="To be a floating button" />
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#00A2E8" />
</LinearLayout>
And what I got is
Upvotes: 1
Views: 805
Reputation: 3167
Thanks to CoordinatorLayout in the Design Support Library this problem can be solved.
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="#22B14C" />
<View
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#00A2E8" />
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
app:backgroundTint="#a349a4"
app:fabSize="normal"
app:layout_anchor="@id/top"
app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>
You have to anchor the FloatingActionButton to the top view using layout_anchor
attribute and then set anchor gravity using layout_anchorGravity
And here is what you get:
Upvotes: 6
Reputation: 11137
The only way you can do this if you want to use the LinearLayout
the way you use it is to define fixed height for the button. You can then achieve the overlay like this
<Button
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginTop="-24dp"
android:layout_marginBottom="-24dp"
android:layout_gravity="center_horizontal"
android:text="To be a floating button"/>
But since it is not a good practice to use layout weights I would suggest to switch to RelativeLayout
.
Upvotes: 0