1. 程式人生 > >android 自定義寬高比的自定義View

android 自定義寬高比的自定義View

這裡以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>