android设置高度比例,Android View设置宽高比

直接上代码(代码可直接复制使用)

1、布局设置

ConstraintLayout 有个属性可以控制比例:layout_constraintDimensionRatio

xmlns:app="http://schemas.android.com/apk/res-auto"

android:id="@+id/constraintLayout"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:layout_width="0dp"

android:layout_height="wrap_content"

android:src="@drawable/head_female_icon"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintDimensionRatio="5:4"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

53f4c21c0f4c

image.png

2、代码设置

//根据宽高比设置控件宽高, 如设置宽高比为5:4,那么widthRatio为5,heightRatio为4

public static void setWidthHeightWithRatio(View view, int width, int widthRatio, int heightRatio) {

if (width <= 0) width = view.getWidth();

int height = width * heightRatio / widthRatio;

ViewGroup.LayoutParams layoutParams = view.getLayoutParams();

if (layoutParams != null) {

layoutParams.height = height;

layoutParams.width = width;

view.setLayoutParams(layoutParams);

}

}

3、自定义控件式

新建RatioRelativeLayout 继承RelativeLayout

import android.content.Context;

import android.content.res.TypedArray;

import android.util.AttributeSet;

import android.widget.RelativeLayout;

/**

* 自定义高宽比布局

*/

public class RatioRelativeLayout extends RelativeLayout {

private float ratio;

public RatioRelativeLayout(Context context) {

super(context);

}

public RatioRelativeLayout(Context context, AttributeSet attrs) {

super(context, attrs);

//获取自定义属性值

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioRelativeLayout);

ratio = typedArray.getFloat(R.styleable.RatioRelativeLayout_ratio, 0.0f);

}

public RatioRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

//获取宽度的模式和尺寸

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

if (ratio != 0) {

//根据宽高比ratio和模式创建一个测量值

heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (widthSize * ratio), MeasureSpec.EXACTLY);

}

//必须调用下面的两个方法之一完成onMeasure方法的重写,否则会报错

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

/**

* 设置高宽比

*

* @param ratio 宽高比(比如:高:宽 = 4:5,ratio=0.8)

*/

public void setRatio(float ratio) {

this.ratio = ratio;

}

}

在styles.xml文件中添加自定义属性

使用

android:id="@id/common_relate_layout_id"

android:layout_width="match_parent"

android:layout_height="wrap_content"

app:ratio="1"/>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值