Android自定義控制元件之自定義ViewGroup實現標籤雲

總李寫程式碼發表於2016-08-01

前言:

     前面幾篇講了自定義控制元件繪製原理Android自定義控制元件之基本原理(一),自定義屬性Android自定義控制元件之自定義屬性(二),自定義組合控制元件Android自定義控制元件之自定義組合控制元件(三),常言道:“好記性不如爛筆頭,光說不練假把式!!!”,作為一名學渣就是因為沒有遵循這句名言才淪落於此,所以要謹遵教誨,注重理論與實踐相結合,今天通過自定義ViewGroup來實現一下專案中用到的標籤雲。

 自定義控制元件相關文章地址:

需求背景:

      公司需要實現一個知識點的標籤顯示,每個標籤的長度未知,如下圖所示

    

基本繪製流程:

繪製原理這裡不再介紹大致介紹下繪製流程

  • 建構函式獲取自定義屬性
  • onMeasure()方法,測量子控制元件的大小
  • onLayout()方法,對子控制元件進行佈局

1.)自定義屬性

<declare-styleable name="TagsLayout">
        <attr name="tagVerticalSpace" format="dimension" />
        <attr name="tagHorizontalSpace" format="dimension" />
</declare-styleable>

2.)建構函式中獲取自定義屬性值

    private int childHorizontalSpace;
    private int childVerticalSpace;

    public TagsLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.TagsLayout);
        if (attrArray != null) {
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagHorizontalSpace, 0);
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagVerticalSpace, 0);
            attrArray.recycle();
        }
    }

3.)onMeasure函式測量子控制元件大小,然後設定當前控制元件大小

@Override
protected LayoutParams generateDefaultLayoutParams() {
return new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

/**
* 負責設定子控制元件的測量模式和大小 根據所有子控制元件設定自己的寬和高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 獲得它的父容器為它設定的測量模式和大小
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
// 如果是warp_content情況下,記錄寬和高
int width = 0;
int height = 0;
/**
* 記錄每一行的寬度,width不斷取最大寬度
*/
int lineWidth = 0;
/**
* 每一行的高度,累加至height
*/
int lineHeight = 0;

int count = getChildCount();
int left = getPaddingLeft();
int top = getPaddingTop();
// 遍歷每個子元素
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE)
continue;
// 測量每一個child的寬和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
// 得到child的lp
ViewGroup.LayoutParams lp = child.getLayoutParams();
// 當前子空間實際佔據的寬度
int childWidth = child.getMeasuredWidth() + childHorizontalSpace;
// 當前子空間實際佔據的高度
int childHeight = child.getMeasuredHeight() + childVerticalSpace;

if (lp != null && lp instanceof MarginLayoutParams) {
MarginLayoutParams params = (MarginLayoutParams) lp;
childWidth += params.leftMargin + params.rightMargin;
childHeight += params.topMargin + params.bottomMargin;
}

/**
* 如果加入當前child,則超出最大寬度,則的到目前最大寬度給width,類加height 然後開啟新行
*/
if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
width = Math.max(lineWidth, childWidth);// 取最大的
lineWidth = childWidth; // 重新開啟新行,開始記錄
// 疊加當前高度,
height += lineHeight;
// 開啟記錄下一行的高度
lineHeight = childHeight;
child.setTag(new Location(left, top + height, childWidth + left - childHorizontalSpace, height + child.getMeasuredHeight() + top));
} else {// 否則累加值lineWidth,lineHeight取最大高度
child.setTag(new Location(lineWidth + left, top + height, lineWidth + childWidth - childHorizontalSpace + left, height + child.getMeasuredHeight() + top));
lineWidth += childWidth;
lineHeight = Math.max(lineHeight, childHeight);
}
}
width = Math.max(width, lineWidth) + getPaddingLeft() + getPaddingRight();
height += lineHeight;
sizeHeight += getPaddingTop() + getPaddingBottom();
height += getPaddingTop() + getPaddingBottom();
setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height);
}

通過遍歷所有子控制元件呼叫measureChild函式獲取每個子控制元件的大小,然後通過寬度疊加判斷是否換行,疊加控制元件的高度,同時記錄下當前子控制元件的座標,這裡記錄座標引用了自己寫的一個內部類Location.java

    /**
     * 記錄子控制元件的座標
     */
    public class Location {
        public Location(int left, int top, int right, int bottom) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        public int left;
        public int top;
        public int right;
        public int bottom;

    }

4.)onLayout函式對所有子控制元件重新佈局

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            Location location = (Location) child.getTag();
            child.layout(location.left, location.top, location.right, location.bottom);
        }
    }

這裡直接遍歷所有子控制元件呼叫子控制元件的layout函式進行佈局。

如何使用:

1.佈局問自己中直接引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:lee="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.whoislcj.views.TagsLayout
        android:id="@+id/image_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        lee:tagHorizontalSpace="10dp"
        lee:tagVerticalSpace="10dp" />

</LinearLayout>

2.)程式碼新增標籤

  TagsLayout imageViewGroup = (TagsLayout) findViewById(R.id.image_layout);
  ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        String[] string={"從我寫程式碼那天起,我就沒有打算寫程式碼","從我寫程式碼那天起","我就沒有打算寫程式碼","沒打算","寫程式碼"};
        for (int i = 0; i < 5; i++) {
            TextView textView = new TextView(this);
            textView.setText(string[i]);
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.round_square_blue);
            imageViewGroup.addView(textView, lp);
        }

具體效果

3.)最後附上TagsLayout全部程式碼

public class TagsLayout extends ViewGroup {
    private int childHorizontalSpace;
    private int childVerticalSpace;

    public TagsLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.TagsLayout);
        if (attrArray != null) {
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagHorizontalSpace, 0);
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagVerticalSpace, 0);
            attrArray.recycle();
        }
    }

    /**
     * 負責設定子控制元件的測量模式和大小 根據所有子控制元件設定自己的寬和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 獲得它的父容器為它設定的測量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        // 如果是warp_content情況下,記錄寬和高
        int width = 0;
        int height = 0;
        /**
         * 記錄每一行的寬度,width不斷取最大寬度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;

        int count = getChildCount();
        int left = getPaddingLeft();
        int top = getPaddingTop();
        // 遍歷每個子元素
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            // 測量每一個child的寬和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            // 當前子空間實際佔據的寬度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + childHorizontalSpace;
            // 當前子空間實際佔據的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + childVerticalSpace;
            /**
             * 如果加入當前child,則超出最大寬度,則的到目前最大寬度給width,類加height 然後開啟新行
             */
            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新開啟新行,開始記錄
                // 疊加當前高度,
                height += lineHeight;
                // 開啟記錄下一行的高度
                lineHeight = childHeight;
                child.setTag(new Location(left, top + height, childWidth + left - childHorizontalSpace, height + child.getMeasuredHeight() + top));
            } else {// 否則累加值lineWidth,lineHeight取最大高度
                child.setTag(new Location(lineWidth + left, top + height, lineWidth + childWidth - childHorizontalSpace + left, height + child.getMeasuredHeight() + top));
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
        }
        width = Math.max(width, lineWidth) + getPaddingLeft() + getPaddingRight();
        height += lineHeight;
        sizeHeight += getPaddingTop() + getPaddingBottom();
        height += getPaddingTop() + getPaddingBottom();
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            Location location = (Location) child.getTag();
            child.layout(location.left, location.top, location.right, location.bottom);
        }
    }

    /**
     * 記錄子控制元件的座標
     */
    public class Location {
        public Location(int left, int top, int right, int bottom) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        public int left;
        public int top;
        public int right;
        public int bottom;

    }
}
TagsLayout.java

總結:

  至此有關簡單的自定義控制元件已經介紹的差不多了,專案中很複雜的控制元件現在涉及的比較少,以後用到之後再做記錄。

 

相關文章