什么是AttributeSet以及如何使用它?

Pre*_*ier 71 android attributes view

什么是Android中的AttributeSet?

我如何将它用于我的自定义视图?

cap*_*wag 22

一个迟到的答案,虽然详细描述,为其他人.

AttributeSet(Android文档)

与XML文档中的标记关联的属性集合.

基本上,如果您尝试创建自定义视图,并且想要传递尺寸,颜色等值,则可以使用AttributeSet.

这是一个例子

想象一下,你想在View下面创建一个类似的东西

在此输入图像描述

有一个黄色背景的矩形,里面有一个圆圈,比方说5dp半径和绿色背景.如果希望视图通过XML获取背景颜色和半径的值,如下所示:

<com.anjithsasindran.RectangleView
    app:radiusDimen="5dp"
    app:rectangleBackground="@color/yellow"
    app:circleBackground="@color/green" />
Run Code Online (Sandbox Code Playgroud)

AttributeSet就是使用的地方.您可以将此文件包含attrs.xml在values文件夹中,并具有以下属性.

<declare-styleable name="RectangleViewAttrs">
    <attr name="rectangle_background" format="color" />
    <attr name="circle_background" format="color" />
    <attr name="radius_dimen" format="dimension" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

由于这是一个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()
    }
}
Run Code Online (Sandbox Code Playgroud)

所以现在我们可以RectangleView在xml布局中使用这些属性,我们将在RectangleView构造函数中获取这些值.

app:radius_dimen
app:circle_background
app:rectangle_background
Run Code Online (Sandbox Code Playgroud)

  • 你为什么在`getDimensionInPixel(50)`中提供一个整数值? (2认同)
  • 感谢您的漂亮回答,它很容易理解。为了提供这个答案,需要提供一些更有用的小信息。完成后回收 TypedArray。这将使以后的调用者重新使用它。 (2认同)

Rob*_*ond 6

AttributeSet是xml资源文件中指定的属性集.您不必在自定义视图中执行任何特殊操作.在View(Context context, AttributeSet attrs)被调用初始化从布局文件的视图.只需将此构造函数添加到自定义视图即可.查看SDK中的自定义视图示例以查看其使用情况.


Dav*_*ave 6

您可以使用AttributeSet为您在xml中定义的视图获取额外的自定义值.例如.有一个关于定义自定义属性的教程,其中指出"可以直接从AttributeSet读取值",但它没有说明如何实际执行此操作.但是,它确实警告说,如果你不使用样式属性,那么:

  • 不解析属性值中的资源引用
  • 样式不适用

如果你想忽略整个样式属性并直接获取属性:

的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>
Run Code Online (Sandbox Code Playgroud)

注意有两行xmlns(xmlns = XML命名空间),第二行定义为xmlns: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
}
Run Code Online (Sandbox Code Playgroud)