Android 控件在布局中按比例放置

转自:http://netsky1990.blog.51cto.com/2220666/997452

      在Android开发中常用到线性布局LinearLayout对界面进行具体的创建,其中 android:layout_weight这个属性很重要,它可以按照程序员的控制,根据终端屏幕的大小,以 相应的比例显示控件的大小,而不会把控件的大小写死,造成无法根据屏幕来自动调整控件本身的大小。

需要注意以下几点:
一、LinearLayout内的控件的 layout_width设置为"wrap_content"
      例:
                  
<pre name="code" class="html"> android:layout_height="fill_parent"
             android:layout_weight="1"
             android:text="1"/>
       
             android:layout_height="fill_parent"
             android:layout_weight="2"
             android:text="1"/>
       
             android:layout_height="fill_parent"
             android:layout_weight="3"
             android:text="1"/>


 
      这个时候3个TextView是按照1:2:3的比例进行显示的,但是 如果TextView内的文本长度过长,则会改变效果,控件并没有按照比例显示大小,比如:
    
                  
 <pre name="code" class="html">android:layout_height="fill_parent"
             android:layout_weight="1"
             android:text="1111111111111111111111111111111111111111111"/>
       
             android:layout_height="fill_parent"
             android:layout_weight="2"
             android:text="1"/>
       
             android:layout_height="fill_parent"
             android:layout_weight="3"
             android:text="1"/>

 
      办法是 设置android:layout_width="wrap_content"为android:layout_width="0dp"。这样控件里的内容并不会影响控件的大小。
二、LinearLayout内的控件的 layout_width设置为"fill_parent"
      例:
fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="1"
             android:text="1"/>
        fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="2"
             android:text="1"/>


      这个时候整个宽度平分为3块,第一个TextView占了两块,也就是 weight值越小的比例越大
      当有三个控件时,问题就来了:
          
 fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="1"
             android:text="1"/>
        fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="2"
             android:text="2"/>
        fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="3"
             android:text="3"/>

      此时 第三个TextView没有显示,把上面三个TextView对应的weight分别改为2,3,4,又可以看到第三个控件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值