/**
* 获取 id值,
*
* @param attribute
* 属性名称
*
* @return 如果找到资源id,否则返回0
*/
public int getId(String attribute) {
String string = getValue(attribute);
if (string != null && string.startsWith("@")) {// 资源id
return Integer.parseInt(string.substring(1));
}
return 0;
}
/**
* 获取尺寸大小 sp,db,dip,px
*
* @param attribute
*
* @return 尺寸大小或者0
*/
public float getDimension(String attribute) {
int id = getId(attribute);
if (id != 0) {
return mContext.getResources().getDimension(id);
}
String string = getValue(attribute) + "";
string = string.toLowerCase();
DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
int unit = -1;
String endStr = "";
if (string.endsWith("sp")) {
unit = TypedValue.COMPLEX_UNIT_SP;
endStr = "sp";
} else if (string.endsWith("dp")) {
unit = TypedValue.COMPLEX_UNIT_DIP;
endStr = "dp";
} else if (string.endsWith("dip")) {
unit = TypedValue.COMPLEX_UNIT_DIP;
endStr = "dip";
} else if (string.endsWith("px")) {
unit = TypedValue.COMPLEX_UNIT_PX;
endStr = "px";
}
try {
float value = Float.parseFloat(string.replace(endStr, ""));
float f = TypedValue.applyDimension(unit, value, dm);
return f;
} catch (Exception e) {
}
return 0;
}
/**
* 获取颜色
*
* @param attribute
*
* @return 颜色值或者0
*/
public int getColor(String attribute) {
String string = getValue(attribute);
int id = getId(attribute);
if (id != 0) {
return mContext.getResources().getColor(id);
}
try {
return Color.parseColor(string);
} catch (Exception e) {
}
return 0;
}
}
AttributeSet 帮助类,读取Android的属性---2
最新推荐文章于 2023-07-10 12:58:55 发布