LinearLayout分隔符妙用

缘起

平时开发中很多时候,我们需要写这样的布局:类似标准的设置界面,从上到下一行一行的条目,然后每个条目之间有道分隔符隔开,就像下图这样:

《LinearLayout分隔符妙用》 标准设置界面中的分隔符

如何优雅地实现

方案1:
这时你可能会想这还不简单,我在每个item view的后面都插一个额外的分隔符view(一条线),就像这样:

《LinearLayout分隔符妙用》 借助View实现

虽然问题也能解决,但不够好、不够优雅。假如是在上面设置界面的case里,那我们可得有不少View需要写在最终的xml里面。如果你的业务又需要在某些情况下隐藏某个条目,那么你还得记得隐藏某条目的时候最好把和它配对的分隔符也隐藏掉,否则2个1px的分隔符会拼在一起,变成了个2px的分隔符,仔细看会发现的,其实已经算是一个小bug了,这样的处理不仅会使逻辑变的复杂,而且很无趣。另外这种方式由于增加了不少View,即LinearLayout的children也包括了这些view,当你想访问LinearLayout的children时也会带来不少麻烦,因为他们也会被算进去的。

方案2:
其实大可不必这么麻烦,LinearLayout已经为了这个很常见的case提供了非常优雅的实现,如下:

《LinearLayout分隔符妙用》 LinearLayout在每项中间显示divider

showDividers:divider显示的位置,默认是none,不显示divider,其它值有beginning(第0个child前面),middle(每个child之间),end(最后一个child后面),这些值可以通过’|’组合起来使用,比如你可以指定”beginning|middle|end”;
divider:具体长什么样的分隔符,是一个drawable,注意这里不能简单只给个颜色值,比如#f00或者@color/xxx这样,drawable一定要是个有长、宽概念的drawable,比如你可以纯粹用一张图片当divider,我们这里用到的pf_linearlayout_horizonal_divider具体的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">    
    <size android:height="1px" />    
    <solid android:color="@color/mgjpf_view_divider_color" />
</shape>

同样的我们有linearlayout_vertical_divider,用在水平的LinearLayout中,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">    
    <size android:width="1px" />    
    <solid android:color="@color/mgjpf_view_divider_color" />
</shape>

dividerPadding:是左右或上下距离LinearLayout的边距,有点margin的意思。你可以随时在自己的demo程序里改变下这个值,然后就能立马在预览区看到效果,帮助你加深理解。

源码分析

我们都知道ViewGroup由于是view容器的关系,所以它默认是啥都不画的,主要是它没啥需要画的,具体需要画那都是某个具体子类做的事情,这个小结论参考如下ViewGroup的源码:

《LinearLayout分隔符妙用》 ViewGroup默认不画任何东西

说完这个小结论,我们继续看下LinearLayout中关于divider支持的源码,涉及到的字段如下:

《LinearLayout分隔符妙用》 相关字段

我们上面说drawable要有长宽概念的,就是对应这里的
mDividerWidth/mDividerWidth字段;

其构造器中有如下的源码:

《LinearLayout分隔符妙用》 LinearLayout构造器

这几个东西就是我们在xml文件中指定的,有具体的divider drawable、showDividers、dividerPadding这些,这里我们只看下
setDividerDrawable实现:

《LinearLayout分隔符妙用》 setDividerDrawable实现

一般情况当我们不指定divider的时候,第一行的if会成立,也就是说这个方法啥也不做就返回了,但当我们指定一个有效的divider时,mDivider会被设置,并且会记录divider的长宽,这2个值在接下来布局、绘制过程中都会用到,最后注意下这里有个setWillNotDraw(divider == null);的调用,换句话说如果没divider,那么LinearLayout还是和ViewGroup一样,啥都不需要画,否则will_not_draw这个flag会被清掉,也就是需要画东西,当然就是需要画具体的divider了。

接下来我们来看下,具体绘制的代码,如下:

    @Override
    protected void onDraw(Canvas canvas) {
        // 如果没divider,那直接返回啥也不需要画
        if (mDivider == null) {
            return;
        }

        if (mOrientation == VERTICAL) {
            drawDividersVertical(canvas);
        } else {
            drawDividersHorizontal(canvas);
        }
    }

    // 在竖直的LinearLayout里画水平的divider
    void drawDividersVertical(Canvas canvas) {
        final int count = getVirtualChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getVirtualChildAt(i);

            // 非GONE的child都会被执行这样的操作
            if (child != null && child.getVisibility() != GONE) {
                // 如果它前面有的话
                if (hasDividerBeforeChildAt(i)) {
                    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                    // 需要画的y坐标起始点
                    final int top = child.getTop() - lp.topMargin - mDividerHeight;
                    drawHorizontalDivider(canvas, top);
                }
            }
        }

        // 检查最后的位置
        if (hasDividerBeforeChildAt(count)) {
            final View child = getLastNonGoneChild();
            int bottom = 0;
            if (child == null) {
                bottom = getHeight() - getPaddingBottom() - mDividerHeight;
            } else {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                bottom = child.getBottom() + lp.bottomMargin;
            }
            drawHorizontalDivider(canvas, bottom);
        }
    }

    /**
     * Determines where to position dividers between children.
     *
     * @param childIndex Index of child to check for preceding divider
     * @return true if there should be a divider before the child at childIndex
     * @hide Pending API consideration. Currently only used internally by the system.
     */
    protected boolean hasDividerBeforeChildAt(int childIndex) {
        if (childIndex == getVirtualChildCount()) {
            // Check whether the end divider should draw.
            return (mShowDividers & SHOW_DIVIDER_END) != 0;
        }
        boolean allViewsAreGoneBefore = allViewsAreGoneBefore(childIndex);
        if (allViewsAreGoneBefore) {
            // This is the first view that's not gone, check if beginning divider is enabled.
            return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0;
        } else {
            return (mShowDividers & SHOW_DIVIDER_MIDDLE) != 0;
        }
    }

    /**
     * Checks whether all (virtual) child views before the given index are gone.
     */
    private boolean allViewsAreGoneBefore(int childIndex) {
        for (int i = childIndex - 1; i >= 0; i--) {
            View child = getVirtualChildAt(i);
            if (child != null && child.getVisibility() != GONE) {
                return false;
            }
        }
        return true;
    }

    // 画水平的divider,只需要知道y方向top坐标即可
    void drawHorizontalDivider(Canvas canvas, int top) {
        mDivider.setBounds(getPaddingLeft() + mDividerPadding, top,
                getWidth() - getPaddingRight() - mDividerPadding, top + mDividerHeight);
        mDivider.draw(canvas);
    }

    // 同样,画竖直的divider,只需要知道x方向left坐标即可
    void drawVerticalDivider(Canvas canvas, int left) {
        mDivider.setBounds(left, getPaddingTop() + mDividerPadding,
                left + mDividerWidth, getHeight() - getPaddingBottom() - mDividerPadding);
        mDivider.draw(canvas);
    }

通过上面的源码分析,我们清楚地知道这种方式要比方案1优雅很多,因为它不需要引入额外的child view,而是通过draw的方式将divider画在合适的位置,相比之下效率也会好很多。而你只需要在xml里面配置几个标签即可,使用方便快捷,事半功倍。

总结

我们平时在用一些很常见的API(如findViewById)、xml写法,这时如果能花点时间搞清楚内部的工作原理,那你在实际使用中才能做到得心应手,对自己写的代码也会充满信心。

    原文作者:tmp_zhao
    原文地址: https://www.jianshu.com/p/1fc54f1cb1d8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞