使用layout_weight属性实现视图的居中显示
16lz
2021-01-23
将按钮居中显示,并且占据其父视图宽度的一半,该如何做呢?
效果图如下:
不同Android设备的尺寸往往是不同的。作为开发者,我们需要创建适用于不同尺寸屏幕的XML文件。硬编码是不可取的。我们可以结合LinearLayout的android:weightSum属性和LinearLayout的子视图的android:layout_weight属性来解决这个问题。
android:weightSum的开发文档里有一段描述如下:
“定义weight总和的最大值。如果未指定该值,以所有子视图的layout_weight属性的累加值作为总和的最大值。一个典型的案例是:通过指定指定子视图的layout_weight属性为0.5,并设置LinearLayout的android:weightSum属性为1.0.实现子视图占据可用宽度的50%。
XML布局文件如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" android:orientation="horizontal" android:weightSum="1"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5" android:text="Click me"/></LinearLayout>
更多相关文章
- Android 属性系统 Property service 设定分析
- 转:android ro.debuggable属性调试修改(mprop逆向)
- Android menu android:showAsAction 属性值详解
- Android学习(2)EditView属性
- Android开发学习笔记:TextView的属性详解
- android学习---通过android帮助学习TextView属性
- android:ellipsize属性的含义