Android开发Android开发经验谈Android技术知识

Android中LinearLayoutCompat的使用

2019-12-04  本文已影响0人  blingbling_5a3f

一.基本使用

LinearLayoutCompat主要作用就是为里面的子View添加分割线,它有三个基本属性。
app:divider="":分割线,类型Drawable;
app:dividerPadding="":分割线的左右内边距;

app:showDividers="":展示分割线的模式,可接收none、beginning、end、middle四种模式。none表示不展示分割线;beginning表示只在第一个子View的前面展示分割线;end表示只在最后一个子View的后面展示分割线;middle表示在每一个子View的中间展示分割线。这些参数也可以组合起来使用,例如:app:showDividers="beginning|middle|end" device-2019-12-04-231706.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添加分割线

device-2019-12-04-233500.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。

四.渐变色分割线

device-2019-12-04-234244.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的属性进行实现,如圆角、分割线高度等,如果碰到需要实现更加复杂的样式,还可以使用图片。

上一篇 下一篇

猜你喜欢

热点阅读