什么是 AttributeSet,我该如何使用它? [英] What is AttributeSet and how can i use it?

查看:35
本文介绍了什么是 AttributeSet,我该如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 Android 中的 AttributeSet?

What is AttributeSet in Android?

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

How can i use it for my custom view?

推荐答案

虽然是详细的描述,但对于其他人来说,答案迟了.

A late answer, although a detailed description, for others.

属性集(Android 文档)

属性的集合,与 XML 文档中的标签相关联.

A collection of attributes, as found associated with a tag in an XML document.

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

Basically if you are trying to create a custom view, and you want to pass in values like dimensions, colors etc, you can do so with AttributeSet.

假设你想创建一个 View 如下所示

Imagine you want to create a View like below

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

There's a rectangle with yellow background, and a circle inside it, with let's say 5dp radius, and green background. If you want your Views to take the values of background colors and radius through XML, like this:

<com.anjithsasindran.RectangleView
    app:radiusDimen="5dp"
    app:rectangleBackground="@color/yellow"
    app:circleBackground="@color/green" />

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

Well that's where AttributeSet is used. You can have this file attrs.xml in values folder, with the following properties.

<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

Since this is a View, the java class extends from 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构造函数中获取这些值.

So now we can use, these properties to our RectangleView in your xml layout, and we will obtain these values in the RectangleView constructor.

app:radius_dimen
app:circle_background
app:rectangle_background

这篇关于什么是 AttributeSet,我该如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆