使用weight属性实现试图的居中显示

来源:互联网 发布:淘宝旺旺名称怎么修改 编辑:程序博客网 时间:2024/05/16 00:53

如果我想将按钮居中显示,并且占据其父视图宽度的一半

效果演示:
这里写图片描述

这里写图片描述

使用windthSum属性和layout_width属性

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:weightSum="1">    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="0.5"        android:text="Hello World!" /></LinearLayout>

其中
android:weightSum=”1” 表示内部所有子视图的weight总和是1,
android:layout_weight=”0.5” 表示Button将占据50%的可用空间

计算 Button 宽度的公式(以屏幕宽度200dp计算)
Button width + Button weight * 200 / sum(weight)

阅读全文
0 0