自定义宽高比例的view(轮播图,item等)

为解决轮播图、listview中的item,放在不通分辨率的手机上会出现拉伸变形。

比较简单  不多说  下边直接贴代码

关于下边方法中

- getPaddingLeft() - getPaddingRight()后又加上是因为
如果view中设置了padding 则会改变正确的比例值

+ 0.5f
因float类型转换int类型是为了减少误差[(49.2+0.5f)=49  (49.7+0.5f)=50]


import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
 * 作者:Created by mengshirui on 2016-07-18
 * 邮箱:
 * 描述:自定义宽高比例的view
 */
public class RatioLayout extends FrameLayout {
	// 宽和高的比例
	private float ratio = 0.0f;
	public RatioLayout(Context context) {
		this(context, null);
	}
	public RatioLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}
	public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		//从xml中获取比例值(需在values下的attrs下声明)
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
		ratio = a.getFloat(R.styleable.RatioLayout_ratio, 0.0f);
		a.recycle();
	}
	/**
	 * 可代码设置,或者布局中设置
    	 * 设置宽高比例
	 * @param f
     */
	public void setRatio(float f) {
		ratio = f;
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
		int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
		//MeasureSpec.EXACTLY精确模式
		if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && ratio != 0.0f) {
			height = (int) (width / ratio + 0.5f);
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + getPaddingTop() + getPaddingBottom(),
					MeasureSpec.EXACTLY);
		} else if (widthMode != MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY && ratio != 0.0f) {
			width = (int) (height * ratio + 0.5f);
			widthMeasureSpec = MeasureSpec.makeMeasureSpec(width + getPaddingLeft() + getPaddingRight(),
					MeasureSpec.EXACTLY);
		}else {
			new RuntimeException("设置比例值,宽高需要一个是精确模式");
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}

在xml中使用的话如下,可直接设置ratia=" "

 
        
    

在values下的  attrs下
 
    
name="RatioLayout">
name="ratio" format="float" />


Android学习手册APP,手机上随时学习 包括(android基础,android组件,用户界面,设备功能,数据储存,网络应用,游戏开发,多媒体,源码开发,高级,android面试题)

http://download.csdn.net/detail/mengshirui_/9576713

你可能感兴趣的:(Android基础)