您的位置:首页 > 其它

自定义固定宽高比例的Layout

2016-07-22 00:00 381 查看
摘要: 该自定义Layout继承自RelativeLayout 使用自定义属性控制比例 可以选择根据宽或者高为标准进行大小控制

java文件

FiexedLayout.java

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import java.io.Serializable;

public class FiexedLayout extends RelativeLayout implements Serializable {

private int mDemoHeight = -1;
private int mDemoWidth = -1;
private String mStandard = "w";

public FiexedLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FiexedLayout, defStyle, 0);
if(a!=null){
mDemoHeight = a.getInteger(R.styleable.FiexedLayout_demoHeight,-1);
mDemoWidth = a.getInteger(R.styleable.FiexedLayout_demoWidth,-1);
mStandard = a.getString(R.styleable.FiexedLayout_standard);
}
}

public FiexedLayout(Context context, AttributeSet attrs) {
this(context, attrs,0);
}

public FiexedLayout(Context context) {
this(context,null);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));

// Children are just made to fill our space.
if(mStandard.length() > 0 && mDemoWidth != -1 && mDemoHeight != -1){
if(mStandard.equals("w")){//以宽为标准
int childWidthSize = getMeasuredWidth();
widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize * mDemoHeight / mDemoWidth, MeasureSpec.EXACTLY);
}else if(mStandard.equals("h")){//以高为标准
int childheightSize = getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(childheightSize, MeasureSpec.EXACTLY);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(childheightSize * mDemoWidth / mDemoHeight, MeasureSpec.EXACTLY);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}


attrs.xml

<declare-styleable name="FiexedLayout">
<attr name="demoHeight" format="integer" />
<attr name="demoWidth" format="integer" />
<attr name="standard" format="string" />
</declare-styleable>

xml布局中引用:

<packageName.FiexedLayout
android:id="@+id/main_users_main_img_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:demoHeight="490"
app:demoWidth="640"
app:standard="w"
android:visibility="visible">

</packageName.FiexedLayout>


其中demoHeight和demoWidth这两个属性不是最终效果显示的宽和高 ,而是用来控制整个view的宽高比

standard这个属性是控制标准的,"w"表示以宽为标准,高度变化,"h" 表示已高为标准宽度变化

本博客原地址:http://my.oschina.net/reone/blog/716238
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息