Android中LinearLayoutCompat的使用
2019-12-04 本文已影响0人
blingbling_5a3f
一.基本使用
LinearLayoutCompat主要作用就是为里面的子View添加分割线,它有三个基本属性。
app:divider="":分割线,类型Drawable;
app:dividerPadding="":分割线的左右内边距;
![](https://img.haomeiwen.com/i13108332/4e36f01a6cecc55b.png)
二.实现左右边距不等的分割线
device-2019-12-04-232526.png
app:dividerPadding="8dp"设置的是左右边距都等于8dp,如要实现上图的需求则需要从drawable入手,可以选择使用inset修改Drawable左右边距。
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="56dp"
android:insetRight="8dp">
<shape android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="#000" />
</shape>
</inset>
三.指定子View添加分割线
![](https://img.haomeiwen.com/i13108332/b50f0132893250b2.png)
上图为前两个Item底部不添加分割线的效果,此时可以选择继承LinearLayoutCompat类,并重写hasDividerBeforeChildAt这个方法,可以在这个方法里面去控制。
public class MyLinearLayoutCompat extends LinearLayoutCompat {
public MyLinearLayoutCompat(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected boolean hasDividerBeforeChildAt(int childIndex) {
int showDividers = getShowDividers();
if (childIndex == 0) {
return (showDividers & 1) != 0;
} else if (childIndex == this.getChildCount()) {
return (showDividers & 4) != 0;
} else if ((showDividers & 2) == 0) {
return false;
} else {
boolean hasVisibleViewBefore = false;
for (int i = childIndex - 1; i > 1; --i) {
if (getChildAt(i).getVisibility() != GONE) {
hasVisibleViewBefore = true;
break;
}
}
return hasVisibleViewBefore;
}
}
}
在循环里面i > 1就是从三个子View开始hasVisibleViewBefore=true。
四.渐变色分割线
![](https://img.haomeiwen.com/i13108332/897edc1216739aa7.png)
可以写一个shape并对shape添加gradient属性:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="#000" />
<gradient
android:endColor="@color/colorPrimary"
android:startColor="@color/colorAccent"
android:type="linear" />
</shape>
其他的很多分割线样式都可以通过设置shape的属性进行实现,如圆角、分割线高度等,如果碰到需要实现更加复杂的样式,还可以使用图片。