Android自定義View——布局Layout

之前寫了一篇文章介紹自定義View,主要是介紹了自定義View繪制相關(guān)的操作。
這里主要是介紹自定義View另一個重要的關(guān)鍵——布局Layout。

繪制相關(guān)介紹可以參考:http://www.itdecent.cn/p/8b96285cda49

自定義布局

自定義布局主要分為兩個部分, 測量(measure()) 和 布局 (layout()
測量過程: 從根view遞歸調(diào)用每一級子view的measure()方法
布局流程:從根view遞歸調(diào)用每一級子view的layout()方法,把測量時得到的子View的尺寸和位置傳遞給子View。

具體的布局流程如下:
1,在xml中編寫View的相關(guān)屬性 (layout_xxx,設(shè)置View的寬高等)
2,父View在自己的onMeasure()方法中,根據(jù)xml中設(shè)置的要求和自己可用的空間,來計算出對子View的尺寸要求,然后調(diào)用子View的measure()方法
3,子View在自己的onMeasure()方法中,根據(jù)自己的特性得出自己的期望尺寸(如果是ViewGroup 會重復(fù)第二步繼續(xù)調(diào)用子View的measure()方法)
4,父View在子View計算出期望尺寸后,得出子View的實際尺?寸和位置保存
5,子View在layout() ?方法中將父 View 傳進(jìn)來的?自?己的實際尺?寸和位置保存(如果是 ViewGroup,還會在 onLayout() ?里里調(diào)?用每個字 View 的layout()把它們的尺?寸 位置傳給它們)

Demo:

下面通過一個demo來展示自定義View的布局,先看效果


標(biāo)簽效果

標(biāo)簽我使用了自定義的View如下,這個屬于自定義view的繪制部分,比較簡單不是本篇文章介紹的重點,這里就不多說了。

public class TagTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final int[] COLORS = {
            Color.parseColor("#E91E63"),
            Color.parseColor("#673AB7"),
            Color.parseColor("#3F51B5"),
            Color.parseColor("#2196F3"),
            Color.parseColor("#009688"),
            Color.parseColor("#FF9800"),
            Color.parseColor("#FF5722"),
            Color.parseColor("#795548")
    };
    private static final Random random = new Random();
    private static final int CORNER_RADIUS = (int) Utils.dp2px(4);
    private static final int X_PADDING = (int) Utils.dp2px(20);
    private static final int Y_PADDING = (int) Utils.dp2px(12);


    private static final int X_LAYOUT = (int) Utils.dp2px(4);
    private static final int Y_LAYOUT = (int) Utils.dp2px(4);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public TagTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        setTextColor(Color.WHITE);
        setTextSize(20);
        paint.setColor(COLORS[random.nextInt(COLORS.length)]);
        setPadding(X_PADDING, Y_PADDING, X_PADDING, Y_PADDING);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRoundRect(X_LAYOUT, Y_LAYOUT, getWidth() - X_LAYOUT, getHeight() - Y_LAYOUT, CORNER_RADIUS, CORNER_RADIUS, paint);
        super.onDraw(canvas);
    }
}

TagLayout 是本篇文章需要介紹的重要內(nèi)容,先看看具體實現(xiàn)。

class TagLayout : ViewGroup {

    var childLayoutList:ArrayList<Rect> = ArrayList()

    constructor(context: Context, attrs: AttributeSet): super(context, attrs) {

    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var viewWidth = 0
        var viewHeight = 0

        var widthMode = MeasureSpec.getMode(widthMeasureSpec)
        viewWidth = MeasureSpec.getSize(widthMeasureSpec)

        var lineWidthUsed = 0
        var lineMaxHeight = 0

        var heightUsed = 0


        for (index in 0 until childCount) {
            var child = getChildAt(index)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)

            if (widthMode != MeasureSpec.UNSPECIFIED && (lineWidthUsed + child.measuredWidth) > viewWidth) {
                lineWidthUsed = 0
                heightUsed += lineMaxHeight
                lineMaxHeight = 0
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)
            }

            var childBounds: Rect
            if (childLayoutList.size <= index) {
                childBounds = Rect()
                childLayoutList.add(childBounds)
            } else {
                childBounds = childLayoutList[index]
            }


            childBounds.set(lineWidthUsed, heightUsed, lineWidthUsed + child.measuredWidth, heightUsed + child.measuredHeight)

            lineWidthUsed += child.measuredWidth
            lineMaxHeight = Math.max(lineMaxHeight, child.measuredHeight)
        }

        // 加上最后一行 標(biāo)簽的高度
        viewHeight = heightUsed + lineMaxHeight

        viewWidth = View.resolveSizeAndState(viewWidth, widthMeasureSpec, 0)
        viewHeight = View.resolveSize(viewHeight, heightMeasureSpec)

        setMeasuredDimension(viewWidth, viewHeight)
    }

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {

        for (index in 0 until childCount) {
            var view = getChildAt(index)
            var bounds = childLayoutList[index]
            view.layout(bounds.left, bounds.top, bounds.right, bounds.bottom)
        }
    }

    // measureChildWithMargins 需要獲取到 margins 需要聲明這個
    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }
}

結(jié)合布局的流程可以看出:
taglayout 主要實現(xiàn)了 onMeasure()onLayout () 兩個函數(shù)。
onMeasure(): 計算了子View的大小并保存子View的位置, 同時計算出自己想要的尺寸大小
onLayout (): 比較簡單,將之前保存的子View尺寸和大小告訴子view。

tips:
1,View.resolveSizeAndState() 一個修正view 尺寸的方法,自定義view中比較常用
2, setMeasuredDimension(viewWidth, viewHeight) 測量完成后需要調(diào)用此方法保存,否則之前測量的就都無效了

END!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容