android:layout_weight 属性详解
2014-06-18 16:01:35  By: shinyuu

在android开发中LinearLayout很常用,LinearLayout的内控件的android:layout_weight在某些场景显得非常重要,比如我们需要按比例显示。

android并没用提供table这样的控件,虽然有TableLayout,但是它并非是我们想象中的像html里面的table那么好用,

我们常用ListView实现table的效果,但是列对齐确比较麻烦,现在用LinearLayout及属性android:layout_weight能很好地解决。

下面我们共同体验下layout_weight这个属性。

一、LinearLayout内的控件的layout_width设置为"wrap_content",请看一下xml配置:

<LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="1">

      <TextView
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"
          android:background="#aa0000"
          android:gravity="center"
          android:text="1"/>

      <TextView
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="2"
          android:background="#00aa00"
          android:gravity="center"
          android:text="1"/>

      <TextView
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="3"
          android:background="#0000aa"
          android:gravity="center"
          android:text="1"/>

  </LinearLayout>

效果如下:

可以看到这三个TextView是按照1:2:3的比例进行显示的,这样看来似乎可以实现按照比例显示了,

但是有个问题,如果TextView内的文本长度一同那么较长文本的TextView会宽度会有所增加,

见下面配置及效果:

android:layout_width="wrap_content"
修改为

android:layout_width="match_parent"
这样就可以了哈

若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力

想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)

或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)

如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教

为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)

感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛


快速评论


技术评论

  • 该技术还没有评论、赶快抢沙发吧...
DD记账
top
+