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

查看:84
本文介绍了什么是 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 的地方.您可以将此文件 attrs.xml 放在 values 文件夹中,并具有以下属性.

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>

由于这是一个View,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天全站免登陆