这里以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) {
int finalWidth = MeasureSpec.getSize(widthMeasureSpec);
int finalHeight = (int) (finalWidth * 9.0f / 16);
super.onMeasure(
MeasureSpec.makeMeasureSpec(finalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(finalHeight, MeasureSpec.EXACTLY));
}
}
先计算出finalWidth的值,再由16:9计算出finalHeight的值,通过super.onMeasure重新赋值
在测试中遇到个问题,这个自定义view在ConstraintLayout内会无效
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#653287"/>
在外面套个Layout就好了
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#653287"/>