首页 > 移动平台 > 详细

Android开发技巧一--weight属性实现视图的居中(半)显示

时间:2015-06-14 09:34:20      阅读:322      评论:0      收藏:0      [点我收藏+]

面试时,一位面试官问到:“如果我想讲按钮居中显示,并且占据其父视图宽度的一半,应该怎么做到呢?”即实现这种效果:

技术分享

我们使用weightSum属性和layout_weight属性实现这一要求:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="center"
    android:weightSum="1" >
    

    <Button
        android:id="@+id/btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="翻  译"
        android:layout_weight="0.5" />
   
        

</LinearLayout>

其中有三个重要的设定

1.设定LinearLayout的android:weightSum属性值为1,表示其内部所有子视图的weight比例总和为1;

2.而LinearLayout中只有唯一的一个子视图Button,因此Button的android:layout_weight="0.5;

3.要想weight属性在水平方向上起作用,那么设置layout_weight的宽度为0dp。

Android开发技巧一--weight属性实现视图的居中(半)显示

原文:http://blog.csdn.net/yayun0516/article/details/46484483

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!