API—TypedArray | Android 开发者
API—AttributeSet | Android 开发者
1 TypedArray的两种初始化方式:
// TypedArray typedArray=context.getTheme().obtainStyledAttributes(R.styleable.mtextview);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.mtextview);
2 TypedArray和AttributeSet的区别
我们用自定义控件1—TextView 中的demo做测试
首先在OneTextView的构造方法中添加测试代码
int attrCount = attrs.getAttributeCount();
//打印AttribuseSet的数量
Log.e("pepe", "AttribuseSet---attrCount="+attrCount);
for (int i = 0; i < attrCount; i++) {
String attrName = attrs.getAttributeName(i);
String attrVal = attrs.getAttributeValue(i);
//打印属性名和对应的属性值
Log.e("pepe", "AttribuseSet---attrName = " + attrName + " , attrVal = " + attrVal);
}
int typedCount=typedArray.getIndexCount();
//打印TypedArray的数量
Log.e("pepe", "TypedArray---typedCount="+typedCount);
//打印自定义的三个属性值
Log.e("pepe", "TypedArray---text = " + mText);
Log.e("pepe", "TypedArray---mTextColor = " + mTextColor);
Log.e("pepe", "TypedArray---mTextSize = " + mTextSize);
接着我对布局中的自定义控件做了修改
<com.pepe.widgetdemo.OneTextView
android:layout_width="100dp"
android:layout_height="100dp"
custom:text="第一个"
custom:textColor="#00ff00"
custom:textSize="20sp"
/>
<com.pepe.widgetdemo.OneTextView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="10dp"
custom:text="@string/twoText"
custom:textColor="@color/twoColor"
custom:textSize="@dimen/twoSize"
/>
对应的string、color、dimen为
<string name="twoText">第二个</string>
<color name="twoColor">#0000ff</color>
<dimen name="twoSize">20sp</dimen>
打印结果如下:
第一个OneTextView
第二个OneTextView
通过对比,可以发现,通过AttributeSet取到的值是原生的
如果xml文件中的值是引用的value,要使用AttributeSet去获得最终的值,需要第一步拿到id,第二步再去解析id。而TypedArray正是帮我们简化了这个过程,取到的则是经过转换的值。
其他:
可能有人会有疑问,打印出来的mTextSize为什么会是60。
这个60的单位是px,是根据测试手机的分辨率转换过来的。
下面提供两个px和sp互相转换的方法:
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
引用:
Android 深入理解Android中的自定义属性 - Hongyang - 博客频道 - CSDN.NET
Android开发学习之TypedArray类 - richerg85的专栏 - 博客频道 - CSDN.NET