现在的位置: 首页 > 综合 > 正文

我的Android进阶之旅——>关于android:layout_weight属性的一个面试题

2013年12月10日 ⁄ 综合 ⁄ 共 2356字 ⁄ 字号 评论关闭


最近碰到一个面试题,按照下图,由Button和EditText组成的界面下厨布局代码,解决这题目需要使用android:layout_weight的知识。

首先分析上图所示的界面可以看成一下3个部分。

  1. 界面顶端的3个按钮。
  2. 界面中间的EditText。
  3. 界面底端的1个按钮。
  • 其中第1部分和第3部分分别在界面顶端和底端显示,而第2部分的EditText充满了剩余的空间。
  • 如果想让一个组件充满整个屏幕,需要将android:layout_width和android:layout_height都设成fill_parent或者match_parent。我们可以将第1部分看成一个整体,android:layout_height的值设成wrap_content,第3部分的android:layout_height的值也设成wrap_content,那么第2部分的<EditText>标签的android:layout_weight属性值要设为一个大于0的浮点数(例如1)。这样EditText就会充满整个剩余空间。否则EditText会占用第3部分的Button空间,这样界面底端的按钮就会显示不出来。
  • 现在来看第1部分的3个按钮。这3个按钮分钟占了水平宽度的1/5、3/5、1/5。这种按比例摆放的组件一般都需要设置标签的android:layout_weight属性。按重要程度可将3个Button的android:layout_weight属性从左到右依次设为2、1、2。
具体的实现布局代码如下所示:

<?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:orientation="vertical" >

    <!-- 顶端的3个按钮布局 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <!-- 该按钮占1/5宽度 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="1/5" />
        
        <!-- 该按钮占3/5宽度 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3/5" />
        
        <!-- 该按钮占1/5宽度 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="1/5" />
    </LinearLayout>
    
    <!-- 充满剩余空间的EditText组件 -->
    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="EditText(充满上方和下方按钮之间的整个屏幕\n博客地址:http://blog.csdn.net/ouyang_peng)" />
	
    <!-- 屏幕底端的按钮 -->
    <Button android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="按钮"/>
</LinearLayout>

    关于android:layout_weight的更多介绍可以参考一下资源:

  1. http://www.cnblogs.com/angeldevil/archive/2012/04/08/2437747.html
  2. http://blog.csdn.net/softmanfly/article/details/7636510
  3. http://developer.android.com/guide/topics/ui/layout/linear.html#Weight
  4. http://www.cnblogs.com/draem0507/archive/2013/05/11/3073508.html
  5. Android 对Layout_weight属性完全解析以及使用ListView来实现表格

==================================================================================================

  作者:欧阳鹏  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址http://blog.csdn.net/ouyang_peng

==================================================================================================

抱歉!评论已关闭.