android 开发技巧(1)--使用 weight 属性实现视图的居中显示

来源:互联网 发布:数据有效性输入空格 编辑:程序博客网 时间:2024/04/29 17:43

无意中在网上看到了一本书《Android开发必知的50个诀窍》,但是我没在网上找到完整的版本,看了前三章,后边的是英语的,自己英语又不行,所以就在网上买了一本,现在呢,我有一个想法,就是把书上的例子跑一下,将遇到的问题解决一下,然后在博客上进行记录,当然不是照抄书本了。随手翻了一下书,也有很多实用的技巧,好多技巧之前都没接触过,准备抽出来时间,慢慢写,希望能坚持下去。
现在写第一篇
先上效果图
这里写图片描述
图片功能描述:将按钮居中显示,并且占据其父视图宽度的一半
布局xml

    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"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:textColor="#000000"    android:text="Click me" /></LinearLayout>

这个功能的实现用到了两个属性:weightSum和layout_weight,下边是一些说明:

“定义 weight 总和的最大值。如果未指定该值,以所有子视
图的 layout_weight 属性的累加值作为总和的最大值。一个典型
的案例是:通过指定子视图的 layout_weight 属性为 0.5,并设置
LinearLayout 的 weightSum 属性为 1.0,实现子视图占据可用宽度
的 50%。”

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

0 0
原创粉丝点击