在开发中有很多场景需要使用的比例矩形,比如图片必须保持一定的宽高比才不会变形。但是如果在gridview中按列排列,如果只是指定了列数的话,在不同分辨率的手机下,每个item的宽度是不定的,直接导致了在高度也不好设置。因此只能自定义按照一定比例的矩形布局才行。
<RatioRectLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/video_thumb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
</RatioRectLayout>
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* Created by zhendanon 5/21/2016.
*/
public class RatioRectLayout extends RelativeLayout {
publicRatioRectLayout(Context context, AttributeSet attrs, int defStyle) {
super(context,attrs, defStyle);
}
publicRatioRectLayout(Context context, AttributeSet attrs) {
super(context,attrs);
}
public RatioRectLayout(Contextcontext) {
super(context);
}
@SuppressWarnings("unused")
@Override
protected voidonMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// For simpleimplementation, or internal size is always 0.
// We dependon the container to specify the layout size of
// our view.We can't really know what it is since we will be
// adding andremoving different arbitrary views and do not
// want thelayout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
// Childrenare just made to fill our space.
intchildWidthSize = getMeasuredWidth();
intchildHeightSize = getMeasuredHeight();
widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize,
MeasureSpec.EXACTLY);
// width :height = 2 : 3; 这里就是控制比例的地方
heightMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize * 3>> 1,
MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
特此记录