1.描述
LinearLayout(线性布局),我们屏幕适配的使用
用的比较多的就是LinearLayout的weight(权重属性),在这一节里,我们会详细地解析
下LinearLayout,包括一些基本的属性,Weight属性的使用,以及比例如何计算,另外还
会说下一个用的比较少的属性:android:divider绘制下划线
本节学习图:
②weight属性详解:
当然,如果我们不适用上述那种设置为0dp的方式,直接用wrap_content和match_parent的话,
则要接着解析weight属性了,分为两种情况,wrap_content与match_parent!另外还要看
LinearLayout的orientation是水平还是竖直,这个决定哪个方向等比例划分
1)wrap_content比较简单,直接就按比例的了
2)match_parent(fill_parent):这个责需要计算了
这个时候就会有疑问了,怎么会这样,这比例是2:1吧,那么three去哪了?代码里面明明有
three的啊,还设置了3的,而1和2的比例也不对耶,1:2:3却变成了2:1:0,怎么会这样呢?
答:这里其实没那么简单的,还是需要我们计算的,网上给出的算法有几种,这里就给出笔者
觉得比较容易理解的一种:
step 1:个个都是fill_parent,但是屏幕只有一个啦,那么1 - 3 = - 2 fill_parent
step 2:依次比例是1/6,2/6,3/6
step 3:先到先得,先分给one,计算: 1 - 2 * (1/6) = 2/3 fill_parent
接着到two,计算: 1 - 2 * (2/6) = 1/3 fill_parent
最后到three,计算 1 - 2 * (3/6) = 0 fill_parent
step 4:所以最后的结果是:one占了两份,two占了一份,three什么都木有
③Java代码设置weight属性:
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT, 1));
3.为LinearLayout设置分割线
①直接在布局中添加一个view,这个view的作用仅仅是显示出一条线,代码也很简单:
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#000000" />
②第二种则是使用LinearLayout的一个divider属性,直接为LinearLayout设置分割线
这里就需要你自己准备一张 线的图片了
1)android:divider设置作为分割线的图片
2)android:showDividers设置分割线的位置,none(无),begining(开始),end(结束),middle(每两个组件间)
3)dividerPadding设置分割线的Padding
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/ktv_line_div"
android:orientation="vertical"
android:showDividers="middle"
android:dividerPadding="10dp"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮3" />
</LinearLayout>
上述代码中我们设置了分割线的图片,以及设置分割线的出现位置,以及设置了padding,就实现了上面的效果!
当然我们也可以在代码中setXxx或者getXxx设置或者获得这些属性的值
使用layout_gravity一些泪水总结:
当 android:orientation="vertical" 时, 只有水平方向的设置才起作用,垂直方向的设置不起作用。
即:left,right,center_horizontal 是生效的。
当 android:orientation="horizontal" 时, 只有垂直方向的设置才起作用,水平方向的设置不起作用。
即:top,bottom,center_vertical 是生效的。