【发布时间】:2011-07-16 01:25:06
【问题描述】:
什么是 Android 中的 AttributeSet?
如何将它用于我的自定义视图?
【问题讨论】:
-
@oae 链接已损坏
标签: android attributes view
什么是 Android 中的 AttributeSet?
如何将它用于我的自定义视图?
【问题讨论】:
标签: android attributes view
一个较晚的答案,虽然是详细的描述,但对于其他人。
属性集(Android 文档)
属性的集合,与 XML 文档中的标签相关联。
基本上,如果您尝试创建自定义视图,并且想要传递尺寸、颜色等值,您可以使用AttributeSet 来实现。
假设你想创建一个View,如下所示
有一个黄色背景的矩形,里面有一个圆圈,假设半径为 5dp,背景为绿色。如果您希望您的视图通过 XML 获取背景颜色和半径的值,如下所示:
<com.anjithsasindran.RectangleView
app:radiusDimen="5dp"
app:rectangleBackground="@color/yellow"
app:circleBackground="@color/green" />
这就是使用AttributeSet 的地方。您可以在 values 文件夹中拥有此文件 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)中提供一个整数值?
当从 XML 布局创建视图时,从资源包中读取 XML 标记中的所有属性并作为 AttributeSet 传递给视图的构造函数
虽然可以直接从AttributeSet读取值,但这样做有一些缺点:
而是将AttributeSet 传递给obtainStyledAttribute()。此方法传回 TypedArray 已被尊重和样式化的值数组。
【讨论】:
您可以使用 AttributeSet 为您在 xml 中定义的视图获取额外的自定义值。例如。有一个关于 Defining Custom Attributes 的教程指出,“可以直接从 AttributeSet 读取值”,但它没有说明如何实际执行此操作。但是,它确实警告说,如果您不使用 styled 属性,那么:
如果你想忽略整个样式属性,直接获取属性:
example.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>
注意有两行xmlns(xmlns = XML命名空间),第二行定义为xmlns:custom。然后在 custom:myvalue 下面定义。
CustomTextView.java
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