android 自定义宽高比的自定义View

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010302327/article/details/81980030

这里以16:9为例,定好宽,高自适应

public class View_16_9 extends View {

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

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

    public View_16_9(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if(getMeasuredWidth() > 0){
            measuredHeight = (int) (9f/16*getMeasuredWidth());
        }
        setMeasuredDimension(measuredWidth,measuredHeight);
    }

}

先super.onMeasure(widthMeasureSpec, heightMeasureSpec);计算出view的measuredWidth值,再由16:9计算出

measuredHeight的值,通过setMeasuredDimension(measuredWidth,measuredHeight);赋值

在测试中遇到个问题,这个自定义view在ConstraintLayout内会无效

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.hyq.hm.openglexo.View_16_9
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#653287"/>
</android.support.constraint.ConstraintLayout>

在外面套个Layout就好了

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.hyq.hm.openglexo.View_16_9
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#653287"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
 

猜你喜欢

转载自blog.csdn.net/u010302327/article/details/81980030