- 直接上代碼(代碼可直接復制使用)
1、布局設置
ConstraintLayout 有個屬性可以控制比例:layout_constraintDimensionRatio
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--寬高比5:4-->
<ImageView
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" />
</android.support.constraint.ConstraintLayout>
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和模式創(chuàng)建一個測量值
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文件中添加自定義屬性
<declare-styleable name="RatioRelativeLayout">
<attr name="ratio" format="float" />
</declare-styleable>
- 使用
<com.yate.jsq.widget.RatioRelativeLayout
android:id="@id/common_relate_layout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ratio="1"/>