什么是 Android 中的 AttributeSet?
我如何使用它为我的自定义视图?
AttributeSet 是在 xml 资源文件中指定的属性集。在自定义视图中,您不必做任何特殊的事情。调用 View(Context context, AttributeSet attrs)以从布局文件初始化视图。只需将此构造函数添加到自定义视图。请查看 SDK 中的 自定义视图示例以了解它的用法。
View(Context context, AttributeSet attrs)
您可以使用 AttributeSet 为您在 xml 中定义的视图获取额外的自定义值。比如说。有一个关于 定义自定义属性的教程声明,“可以直接从 AttributeSet 读取值”,但没有说明如何实际做到这一点。但是,它警告说,如果不使用 风格属性,那么:
如果你想忽略整个样式化属性的事情,只是直接得到属性:
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。然后在这个自定义下面: myvalue 被定义。
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 (Android Docs)
与 XML 文档中的标记关联的属性集合。
基本上,如果您试图创建一个自定义视图,并希望传入尺寸、颜色等值,那么可以使用 AttributeSet。
AttributeSet
假设您想创建如下所示的 View
View
有一个黄色背景的矩形,里面有一个圆,半径为5dp,背景为绿色。如果希望视图通过 XML 获取背景颜色和半径的值,如下所示:
<com.anjithsasindran.RectangleView app:radiusDimen="5dp" app:rectangleBackground="@color/yellow" app:circleBackground="@color/green" />
这就是使用 AttributeSet的地方。您可以将这个文件 attrs.xml放在 value 文件夹中,具有以下属性。
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>
因为这是一个 View,所以 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构造函数中获得这些值。
RectangleView
app:radius_dimen app:circle_background app:rectangle_background
当从 XML 布局创建视图时,XML 标记中的所有属性都从资源包中读取,并作为 AttributeSet传递给视图的构造函数
虽然可以直接从 AttributeSet读取值,但这样做有一些缺点:
取而代之的是将 AttributeSet传递给 obtainStyledAttribute()。这个方法将已经被延迟和样式化的值的 TypedArray数组传递回来。
obtainStyledAttribute()
TypedArray