为解决轮播图、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();
}
/**
* 可代码设置,或者布局中设置
<span style="white-space:pre"> </span> * 设置宽高比例