What is AttributeSet and how can i use it?

前端 未结 4 527
谎友^
谎友^ 2020-12-24 00:04

What is AttributeSet in Android?

How can i use it for my custom view?

4条回答
  •  离开以前
    2020-12-24 00:36

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

    AttributeSet (Android Docs)

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

    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.

    Here's an example

    Imagine you want to create a View like below

    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:

    
    

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

    
        
        
        
    
    

    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()
        }
    }
    

    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
    

提交回复
热议问题