admin
2024-01-26 c2d382d99ca506932985d1843d4371d6ed0203ff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.lcjian.library.widget;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
 
import com.lcjian.lcjianlibrary.R;
 
public class RatioLayout extends RelativeLayout {
 
    private float mRatio;
 
    public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
 
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.RatioLayout, defStyle, 0);
        mRatio = a.getFloat(R.styleable.RatioLayout_ratio, 1);
        a.recycle();
    }
 
    public RatioLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
 
    public RatioLayout(Context context) {
        this(context, null);
    }
 
    @SuppressWarnings("unused")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // For simple implementation, or internal size is always 0.
        // We depend on the container to specify the layout size of
        // our view. We can't really know what it is since we will be
        // adding and removing different arbitrary views and do not
        // want the layout to change as this happens.
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec));
 
        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        int childHeightSize = getMeasuredHeight();
        // if(childWidthSize > childHeightSize) {
        // childWidthSize = childHeightSize;
        // }else {
        // childHeightSize = childWidthSize;
        // }
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize,
                MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                (int) (childWidthSize * mRatio), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
 
    public void setRatio(float ratio) {
        mRatio = ratio;
        requestLayout();
    }
}