什么是Android中的AttributeSet?
我如何在自定义视图中使用它?
什么是Android中的AttributeSet?
我如何在自定义视图中使用它?
虽然晚了些,但为其他人提供详细描述。
AttributeSet(Android文档)
一组属性,如在XML文档中与标记相关联所发现的属性。
基本上,如果您正在尝试创建自定义视图,并且想要通过AttributeSet
传递诸如尺寸、颜色等值,那么您可以这样做。
想象一下您想创建如下的View
:
其中有一个黄色背景的矩形和一个圆形,在矩形内部,其半径为5dp,背景为绿色。如果您希望通过XML使您的视图接受背景颜色和半径值,就像这样:
<com.anjithsasindran.RectangleView
app:radiusDimen="5dp"
app:rectangleBackground="@color/yellow"
app:circleBackground="@color/green" />
那就是 AttributeSet
的使用场景。你可以在值文件夹中拥有名为 attrs.xml
的文件,并具备以下属性。
<declare-styleable name="RectangleViewAttrs">
<attr name="rectangle_background" format="color" />
<attr name="circle_background" format="color" />
<attr name="radius_dimen" format="dimension" />
</declare-styleable>
因为这是一个视图,所以Java类需要继承自View
public class RectangleView extends View {
public RectangleView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.RectangleViewAttrs);
mRadiusHeight = attributes.getDimensionPixelSize(R.styleable.RectangleViewAttrs_radius_dimen, getDimensionInPixel(50));
mCircleBackgroundColor = attributes.getDimensionPixelSize(R.styleable.RectangleViewAttrs_circle_background, getDimensionInPixel(20));
mRectangleBackgroundColor = attributes.getColor(R.styleable.RectangleViewAttrs_rectangle_background, Color.BLACK);
attributes.recycle()
}
}
现在我们可以在XML布局中为RectangleView
使用这些属性,并在RectangleView
构造函数中获取这些值。
app:radius_dimen
app:circle_background
app:rectangle_background
getDimensionInPixel(50)
中提供了一个整数值? - Daksh Gargasexample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://www.chooseanything.org">
<com.example.CustomTextView
android:text="Blah blah blah"
custom:myvalue="I like cheese"/>
</LinearLayout>
public CustomTextView( Context context, AttributeSet attrs )
{
super( context, attrs );
String sMyValue = attrs.getAttributeValue( "http://www.chooseanything.org", "myvalue" );
// Do something useful with sMyValue
}
AttributeSet是在xml资源文件中指定的属性集。在自定义视图中,您不需要进行任何特殊操作。 View(Context context, AttributeSet attrs)
会被调用以从布局文件初始化视图。只需将此构造函数添加到自定义视图中即可。请查看SDK中的Custom View示例以查看其用法。
android-sdk\samples\android-17\ApiDemos\src\com\example\android\apis\view
文件夹中。 - Sundeep当从XML布局创建视图时,会从资源包中读取XML标记中的所有属性,并将它们作为AttributeSet
传递给视图的构造函数
尽管可以直接从AttributeSet
读取值,但这样做有一些缺点:
取而代之的是,将AttributeSet
传递给obtainStyledAttribute()
。该方法返回已经被解除引用和设置样式的值的TypedArray
数组。