在有些APP中我们需要实现一个悬浮按钮,比如图片浏览应用左右翻页功能,比如左侧悬浮功能按钮。我们要实现此功能时,最开始想到的就是用FrameLayout来实现,但是如果把按钮简单的放到FrameLayout中,按钮只能在布局的左上角,并不能达到我们的要求。
那么如何才能让按钮放到布局的左侧中间位置呢,开始时想把按钮高度设置成match_parent,然后图片垂直居中,但是这样整个最左侧的部分都是按钮了,显然会影响其他功能的使用,后来想哪个组件才能自由的让子控件放到想放的位置呢,这个得是RelativeLayout了吧。于是在FrameLayout中放了一个RelavtiveLayout中,然后把按钮放到里面,Layout Parameters中的Align Parent Left设置成true,Center Vertical设置成true,再看一下,一个居中的悬浮按钮就弄好了。
同样的方式可以设置其他需要的悬浮按钮了。
附上实现的xml布局代码
XHTML
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hoverbuttontest.MainActivity" >
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button" />
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hoverbuttontest.MainActivity">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button"/>
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button"/>
打赏
微信扫一扫,打赏作者吧~