zoukankan      html  css  js  c++  java
  • Android中设置半个屏幕大小且居中的button布局 (layout_weight属性)

            先看例如以下布局 : 


    上图中。按钮的大小为屏幕的一半,然后居中显示在布局中央,每一个人心中都有自己的答案,看看我的方法吧,布局布局xml例如以下 : 

    <?

    xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" android:gravity="center" android:orientation="horizontal" android:weightSum="1" > <!-- 1.将LinearLayout的layout_weight设置为1 --> <!-- 2.将Button的layout_width设为0dp, 而且将layout_weight设置为0.5 --> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5" android:textSize="13sp" android:text="@string/button_text" > </Button> </LinearLayout>

    这里有几个关键点:

    1. 布局为LinearLayout,以便能够设置layout_weight。
    2. 设置LinearLayout的android:weightSum的值为1;
    3. 将Button的layout_width设置为0dp;
    4. 将Button的layout_weight的值设置为0.5。 即上面的android:weightSum的一半。
    通过上面的设置就能够实现上图中的布局了。

    子空间的宽度算法能够參考例如以下公式, 子控件宽度 = 子控件layout_width + 子控件的layout_weight * 父控件的宽度 / 父控件的layout_weight, 对照上面的样例就是子控件的宽度 = 0.5 * 父控件的宽度 / 1 = 父控件宽度 * 0.5。 由于父控件的宽度为match_parent,所以父控件宽度的宽度为整个屏幕的宽度,所以子控件的宽度 = 0.5 * 整个屏幕的宽度 = 半屏宽度。



  • 相关阅读:
    DNS原理入门
    软件架构入门
    熵:宇宙的终极规则
    新鲜事
    加密货币的本质
    汇编语言入门教程
    HTML & CSS
    [模板] 矩阵快速幂
    [模板] 三分
    [模板] 2-SAT 问题
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/6956477.html
Copyright © 2011-2022 走看看