自定义View实践篇(2)- 自定义ViewGroup

1. 简介

上一章:自定义View实践篇(1)- 自定义单一View
我们实现了自定义单一View,这章我们来看下自定义ViewGroup

2. 自定义ViewGroup

自定义ViewGroup同样分为两类,一类是继承系统已有的ViewGroup(如:LinearLayout),另一类是直接继承ViewGroup类,我们分开来看下。

2.1 继承系统已有ViewGroup

这种方式可以去扩展系统已有ViewGroup的功能,最常用的就是组合View。通过组合不同的View来形成一个新的布局,达到多次复用的效果。比如微信底部导航栏,就是上面一个ImageView,下面一个TextView来组合而成。如下图:
自定义View-微信导航栏.png
我们这里来简单实现一下这个布局,主要是组合一个ImageViewTextView,然后自定义属性可以修改图标和标题:

2.1.1 定义组合View的xml布局

首先我们来定义这个View的布局,就是上面一个ImageView,下面一个TextView,外面使用了LinearLayout来包裹。非常简单,命名为navigation_button.xml

<?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:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

2.1.2 编写组合View的Java代码

接下来,我们编写组合ViewJava代码,由于上面的布局是使用了LinearLayout来包裹,因此我们这里的类也是继承于LinearLayout

public class NavigationButton extends LinearLayout {//继承于LinearLayout

    private ImageView mIconIv;
    private TextView mTitleTv;

    public NavigationButton(Context context) {
        super(context);
        init(context);
    }

    public NavigationButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public NavigationButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    //初始化
    public void init(Context context) {
        //加载布局
        LayoutInflater.from(context).inflate(R.layout.navigation_button, this, true);
        mIconIv = findViewById(R.id.iv_icon);
        mTitleTv = findViewById(R.id.tv_title);
    }

    //提供一个修改标题的接口
    public void setText(String text) {
        mTitleTv.setText(mText);
    }
}

重写了三个构造方法并在构造方法中加载布局文件,对外提供了一个接口,可以用来设置标题的名字。

2.1.3 自定义属性

为了方便使用,通常我们都会自定义属性,这里定义两个属性:icontitlevalues目录下定义attrs_navigation_button.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NavigationButton">
        <attr name="icon" format="reference"/>
        <attr name="text" format="string"/>
    </declare-styleable>
</resources>

2.1.4 解析自定义属性

将上面的NavigationButton修改一下:

public class NavigationButton extends LinearLayout {

    private ImageView mIconIv;
    private TextView mTitleTv;
    private Drawable mIcon;
    private CharSequence mText;

    public NavigationButton(Context context) {
        super(context);
        init(context);
    }

    public NavigationButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        //解析自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationButton);
        mIcon = typedArray.getDrawable(R.styleable.NavigationButton_icon);
        mText = typedArray.getText(R.styleable.NavigationButton_text);
        //获取资源后要及时回收
        typedArray.recycle();

        init(context);

    }

    public NavigationButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.navigation_button, this, true);
        mIconIv = findViewById(R.id.iv_icon);
        mTitleTv = findViewById(R.id.tv_title);

        //设置相关属性
        mIconIv.setImageDrawable(mIcon);
        mTitleTv.setText(mText);
    }

    public void setText(String text) {
        mTitleTv.setText(mText);
    }
}

2.1.5 使用组合View

<?xml version="1.0" encoding="utf-8"?>
<!--必须添加schemas声明才能使用自定义属性-->
<!--添加的是xmlns:app="http://schemas.android.com/apk/res-auto"-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:gravity="bottom"
    android:orientation="horizontal">

    <com.april.view.NavigationButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        app:icon="@drawable/chats_green"
        app:text="微信">
    </com.april.view.NavigationButton>

    <com.april.view.NavigationButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        app:icon="@drawable/contacts"
        app:text="通讯录">
    </com.april.view.NavigationButton>

    <com.april.view.NavigationButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        app:icon="@drawable/discover"
        app:text="发现">
    </com.april.view.NavigationButton>

    <com.april.view.NavigationButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        app:icon="@drawable/about_me"
        app:text="我">
    </com.april.view.NavigationButton>

</LinearLayout>

运行结果为:
自定义View-NavigationButton.png

2.1.7 总结

组合View非常简单,只需继承系统某个已存在的ViewGroup即可,组装好布局以及添加一些自定义属性即可使用,一般无需处理测量、布局、绘制等过程。
通过组合View的方式来实现新的效果,可以使得这个View能够复用起来,维护修改起来时也更方便简单一点。
当然上面的UI效果有更好的方式去实现,这里只是为了举例说明而已。

2.2 继承ViewGroup类

继承ViewGroup类可以用来重新定义一种布局,只是这种方式比较复杂,需要去实现ViewGroup的测量和布局过程以及处理子元素的测量和布局。组合View也可以采用这种方式来实现,只是需要处理的细节更复杂而已。

我们这里来实现一个流式布局,什么是流式布局呢?流式布局就是加入此容器的View从左往右依次排列,如果当前行的宽度不够装进下一个View,就会自动将该View放到下一行中去。如下图所示:
自定义View-流式布局.png

2.2.1 需求分析

首先我们对这个需求进行简单的分析:

  1. 流式布局需要对每个子View进行布局,即从左往右依次摆放,当前行的宽度不够则从下一行开始。
  2. 流式布局需要测量和计算自身的宽高。
  3. 流式布局需要处理marginpadding等细节。
  4. 流式布局需要对外提供一些自定义属性,方便用户去使用。比如可以设置行间距和水平间距等等。

2.2.2 实现步骤

根据上面的需求分析,其实现步骤如下:

  1. 自定义属性。
  2. 解析自定义属性以及对外提供一些设置属性的接口等。
  3. 重写onMeasure(),实现自身的测量过程。
  4. 重写onLayout(),对子View的位置进行布局。
  5. 使用自定义View

2.2.3 自定义属性

这里定义两个属性:行间距,水平间距,values目录下定义attrs_flow_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FlowLayout">
        <!--水平间距-->
        <attr name="horizontal_spacing" format="dimension|reference"/>
        <!--行间距-->
        <attr name="vertical_spacing" format="dimension|reference"/>
    </declare-styleable>
</resources>

2.2.4 解析自定义属性

对自定义的属性进行解析,以及对外提供一些设置属性的接口:

public class FlowLayout extends ViewGroup {//继承ViewGroup

    private int mHorizontalSpacing;//水平间距
    private int mVerticalSpacing;//行间距
    //默认间距
    public static final int DEFAULT_Horizontal_SPACING = 10;
    public static final int DEFAULT_Vertical_SPACING = 10;

    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        //解析自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
        mHorizontalSpacing = typedArray.getDimensionPixelOffset(R.styleable.FlowLayout_horizontal_spacing, DEFAULT_Horizontal_SPACING);
        mVerticalSpacing = typedArray.getDimensionPixelOffset(R.styleable.FlowLayout_vertical_spacing, DEFAULT_Vertical_SPACING);
        //获取资源后要及时回收
        typedArray.recycle();

    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //设置水平间距
    public void setHorizontalSpacing(int pixelSize) {
        mHorizontalSpacing = pixelSize;
        requestLayout();
    }

    //设置行间距
    public void setVerticalSpacing(int pixelSize) {
        mVerticalSpacing = pixelSize;
        requestLayout();
    }
}

2.2.5 重写onMeasure()

具体解析见下面代码注释,需要注意的是,我们这里支持margin,所以会复杂点。

    private List<Integer> mHeightLists = new ArrayList<>();//保存每行的最大高度

    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        //因为我们需要支持margin,所以需要重写generateLayoutParams方法并创建MarginLayoutParams对象
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 获得测量模式和大小
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        // 如果是warp_content情况下,记录宽和高
        int warpWidth = 0;
        int warpHeight = 0;

        int widthUsed = getPaddingLeft() + getPaddingRight();//Padding的宽度
        int lineWidth = widthUsed;//记录当前行的宽度
        int lineHeight = 0;//记录一行的最大高度

        int childCount = getChildCount();
        //遍历子View进行测量
        for (int i = 0; i < childCount; i++) {

            View child = getChildAt(i);

            //子View为GONE则跳过
            if (child.getVisibility() == View.GONE) {
                continue;
            }
            //获得一个支持margin的布局参数
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            //测量每个child的宽高,每个child可用的最大宽高为widthSize-padding-margin
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

            // child实际占据的宽高
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            //判断这一行是否还能装得下这个child
            if (lineWidth + childWidth <= widthSize) {
                //装得下,则累加这一行的宽度,并记录这一行的最大高度
                lineWidth += childWidth + mHorizontalSpacing;
                lineHeight = Math.max(lineHeight, childHeight);
            } else {//装不下,需要换行,则记录这一行的宽度,高度,下一行的初始宽度,初始高度

                //比较当前行宽度(当前行宽度需减去末尾的水平间距)与下一行宽度,取最大值
                warpWidth = Math.max(lineWidth - mHorizontalSpacing, widthUsed + childWidth);
                //换行,记录新行的初始宽度
                lineWidth = widthUsed + childWidth + mHorizontalSpacing;

                //累加当前高度
                warpHeight += lineHeight + mVerticalSpacing;
                //保存每行的最大高度,onLayout时会用到
                mHeightLists.add(lineHeight);
                //记录下一行的初始高度,并设置为当前行
                lineHeight = childHeight;
            }

            // 如果是最后一个child,则将当前记录的最大宽度和当前lineWidth做比较
            if (i == childCount - 1) {
                warpWidth = Math.max(warpWidth, lineWidth - mHorizontalSpacing);
                //累加高度
                warpHeight += lineHeight;
            }
        }
        //根据测量模式去保存相应的测量宽度
        //即如果是MeasureSpec.EXACTLY直接使用父ViewGroup传入的宽和高
        //否则设置为自己计算的宽和高,即为warp_content时
        setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize : warpWidth,
                (heightMode == MeasureSpec.EXACTLY) ? heightSize : warpHeight);
    }

2.2.6 重写onLayout()

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int width = getWidth();
        int line = 0;//当前行号
        int widthUsed = getPaddingLeft() + getPaddingRight();//Padding的宽度
        int lineWidth = widthUsed;//记录当前行的宽度
        int left = getPaddingLeft();
        int top = getPaddingTop();

        int childCount = getChildCount();
        //遍历所有子View
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);

            //child为GONE则跳过
            if (child.getVisibility() == View.GONE) {
                continue;
            }

            //获得一个支持margin的布局参数
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //获取child的测量宽度
            int childWidth = child.getMeasuredWidth();
//            int childHeight = child.getMeasuredHeight();

            //判断这一行是否还能装得下这个child,需要把margin值加上
            if (lineWidth + childWidth + lp.leftMargin + lp.rightMargin <= width) {
                //装得下,则累加这一行的宽度
                lineWidth += childWidth + mHorizontalSpacing;
            } else {//装不下,需要换行,则记录新行的宽度,并设置新的left、top位置
                //重置left
                left = getPaddingLeft();
                //top累加当前行的最大高度和行间距
                top += mHeightLists.get(line++) + mVerticalSpacing;
                //开始新行,记录宽度
                lineWidth = widthUsed + childWidth + mHorizontalSpacing;
            }
            //计算child的left,top,right,bottom
            int lc = left + lp.leftMargin;
            int tc = top + lp.topMargin;
            int rc = lc + child.getMeasuredWidth();
            int bc = tc + child.getMeasuredHeight();
            //计算child的位置
            child.layout(lc, tc, rc, bc);
            //left往右移动一个水平间距
            left = rc + mHorizontalSpacing;
        }
    }

2.2.7 使用自定义View

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">

    <com.april.view.FlowLayout
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#0ff"
        android:padding="5dp"
        app:horizontal_spacing="10dp"
        app:vertical_spacing="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="Android"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="源码分析"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="自定义View"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="继承系统已有View"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="继承View类"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="继承ViewGroup类"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="继承系统已有ViewGroup"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bg"
            android:text="自定义属性"/>

    </com.april.view.FlowLayout>
</LinearLayout>

运行程序,结果为:
自定义View-FlowLayout.png

2.2.8 总结

继承ViewGroup类来实现一个全新的布局,一般来说都要重写onMeasure()onLayout(),以及提供自定义属性。但是onDraw()一般不需要重写,除非要实现一些分割线之类的需求。

总的来说,继承ViewGroup类是最复杂的,要写出一个好的自定义的ViewGroup,需要注意非常多的细节,比如marginpadding等等。

另外,上面的FlowLayout实际上还不够好,还有很多细节没实现,比如支持gravity等等,可能还会有一些bug,但是作为一个例子来说明继承ViewGroup类这种自定义View的方式还是足够的。

如果需要使用流式布局,实际google也为我们开源了一个控件,有兴趣的可以去看下FlexboxLayout

猜你喜欢

转载自blog.csdn.net/u011810352/article/details/79486938