Android 自定义控件获取布局宽高
通过构造方法的AttributeSet 获取xml布局文件上定义的宽高
public int getViewHeight(AttributeSet attributeSet, Context context) {
String layout_height = context.getString(attributeSet.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "layout_height", 0));
int height = Integer.parseInt(layout_height.substring(0, layout_height.indexOf(".")));
return DisplayUtil.dip2px(context, height);
}
public int getViewWidth(AttributeSet attributeSet, Context context) {
String layout_width = context.getString(attributeSet.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "layout_width", 0));
int width= Integer.parseInt(layout_width.substring(0, layout_width.indexOf(".")));
return DisplayUtil.dip2px(context, width);
}
AttributeSet.getAttributeResourceValue(String namespace, String attribute, int defaultValue)
参数:
namespace: 属性的命名空间,android内置命名空间为http://schemas.android.com/apk/res/android,自定义属性填null即可
attribute: 属性名称
defaultValue: 如果属性为null返回的默认值
官方解释地址: https://developer.xamarin.com/api/member/Android.Util.IAttributeSet.GetAttributeResourceValue/p/System.String/System.String/System.Int32/
附转换方法
/**
* dp转换成px
*
* @param context context对象
* @param dpVale dp值
* @return px值
*/
public static int dip2px(Context context, float dpVale) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpVale * scale + 0.5f);
}
/**
* sp转换成px
*
* @param context context对象
* @param spValue sp值
* @return px值
*/
public static int dip2sp(Context context, float spValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());
}
/**
* px转换成dp
*
* @param context context对象
* @param pxValue px值
* @return dp值
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}