Android 指定寬高比的ViewGroup

開發(fā)中有時(shí)需要固定一個(gè)控件的寬高比, 有時(shí)候是View類型的,有時(shí)候是ViewGroup類型的,這兩者的實(shí)際實(shí)現(xiàn)是有一些區(qū)別的.

例如,有時(shí)候開發(fā)一個(gè)相冊(cè)界面,這種類型的

image.png

我們可以指定RecyclerView單個(gè)item的ImageView寬度為屏幕寬度的1/4,然后通過內(nèi)邊距來控制間隔,可以這樣來實(shí)現(xiàn)

public class SquareImageView extends ImageView {
      //屏幕寬度
      private int screenWidth;
      private int ratio = 4;
        // 省略...

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
             // 保存測(cè)量結(jié)果即可, 指定寬高相等
            setMeasuredDimension(screenWidth / ratio, screenWidth / ratio);
        }
}

View類型的指定寬高比,基本上都是這樣來實(shí)現(xiàn)的,測(cè)量時(shí)保存自己想要的測(cè)量的結(jié)果即可

ViewGroup的實(shí)現(xiàn)方式上有所差別, ViewGroup可以包含childView, 不同于View, 還需要measureChild, 否則child的width,height就始終等于0,未被初始化

例如實(shí)現(xiàn)一個(gè)寬高比16:9的FrameLayout

public class RatioFrameLayout extends FrameLayout {
    
        // 寬高比
        private static final float RATIO = 16.f / 9;
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            // 獲取寬度
            int Width = MeasureSpec.getSize(widthMeasureSpec);
            // 設(shè)置當(dāng)前控件寬高
            setMeasuredDimension(parentWidth, (int) (parentWidth/RATIO));
        }
    }

以上做法,可以確定FrameLayout的寬高比一定是16:9, 但是如果此ViewGroup包含childView, 那么childView將不顯示, 因?yàn)椴]有主動(dòng)去measureChildren

正確的onMeasure回調(diào)應(yīng)該這樣處理

@Override
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            // 父控件是否是固定值或者是match_parent
            int mode = MeasureSpec.getMode(widthMeasureSpec);
            if (mode == MeasureSpec.EXACTLY) {
                // 得到父容器的寬度
                int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
                // 得到子控件的寬度
                int childWidth = parentWidth - getPaddingLeft() - getPaddingRight();
                // 計(jì)算子控件的高度
                int childHeight = (int) (childWidth / RATIO + 0.5f);
                // 計(jì)算父控件的高度
                int parentHeight = childHeight + getPaddingBottom() + getPaddingTop();
                // note 必須測(cè)量子控件,確定孩子的大小
                int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);
                int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
                measureChildren(childWidthMeasureSpec, childHeightMeasureSpec);
                // 測(cè)量
                setMeasuredDimension(parentWidth, parentHeight);
            } else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
    
        }

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

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

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