Android细节—— 权重预分配

来源:互联网 发布:万国数据事件 编辑:程序博客网 时间:2024/06/14 20:11
在写布局时,有部分道友在使用权重时习惯了只在子控件上面加上android:layout_weight="?",习惯之后却忽略了LinearLayout 有一个属性:android:weightSum="?"
android:weightSum的作用在于当前LinearLayout 权重的预分配,其亮点在于:在某些情况下节约资源简化代码,不限制子控件的权重是否超出预分配值。
实用性举例:
(一):预分配
<?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:weightSum="4"
    android:orientation="vertical">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#d7bbbb"
        android:layout_weight="1" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#8c2b2b"
        android:layout_weight="1" />
    
</LinearLayout>

效果如图

预分配的好处在于填充控件时只填充其所占大小,其余的空余,节省了控件开销和市布局更简洁。

(二)非限制 (为了使效果显而易见第一个TextView权重设置为0.9)

<?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:weightSum="1"
    android:orientation="horizontal">


    <TextView
        android:layout_width="0dp"
       
  android:layout_height="match_parent"
       
  android:background="#d7bbbb"
       
  android:layout_weight="0.9" />


    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#8c2b2b"
        android:layout_weight="1" />
</LinearLayout>

效果如图:

代码里面加上触控监听和动画就有一个简单滑动菜单了,菜单宽度还是权重值适配性高

0 0