使用layout_weight属性实现视图的居中显示

来源:互联网 发布:腾讯网络电视 编辑:程序博客网 时间:2024/05/16 01:07

将按钮居中显示,并且占据其父视图宽度的一半,该如何做呢?

效果图如下:

竖屏

横屏

不同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>
0 0
原创粉丝点击