1. 程式人生 > >RelativeLayout 長寬自適應(按比例)

RelativeLayout 長寬自適應(按比例)

attrs.xml

    <!-- 長寬比 -->
    <declare-styleable name="ScaleLayout">
        <attr name="widthToHeight" format="float" />
    </declare-styleable>

ScaleLayout.java

/**
 * 長寬自適應(按比例)
 * @email [email protected]
 * @author Aman
 *
 */
public class ScaleLayout extends RelativeLayout {
float defaultWidthToHeight = 1.0f;//長寬預設1:1
float widthToHeight;
    private WeakReference<Context> wr;
    public ScaleLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    wr= new WeakReference<Context>(context);
    // get system attrs (android:textSize and android:textColor)
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ScaleLayout); 
    widthToHeight = a.getFloat(R.styleable.ScaleLayout_widthToHeight, defaultWidthToHeight);
    a.recycle();
    }


    public ScaleLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    wr= new WeakReference<Context>(context);
    }


    public ScaleLayout(Context context) {
        this(context,null);
    wr= new WeakReference<Context>(context);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), (int) (getDefaultSize(0, widthMeasureSpec)*widthToHeight));
        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        int childHeightSize =  getMeasuredHeight() ;
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
        
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
    }
}

使用:

<ScaleLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:attr="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    attr:widthToHeight="1.5"
    android:layout_height="match_parent"
    android:orientation="vertical" >

.......

</ScaleLayout>