SamHoque
SamHoque

Reputation: 3154

Getting attribute value from view object

I have a custom View object, and I only have access to the View. So, I have an attribute called attribute1 and I have set it for my view using app:attribute1="value" how can I retrive the attribute value from just my View object, is this even possible? what approches can I take for this? I have searched almost everywhere and couldn't find anything about it.

Example:

CustomView customView = new CustomView();

I would like to get the attribute value from customView

Upvotes: 2

Views: 1419

Answers (2)

Ben P.
Ben P.

Reputation: 54204

XML attributes are available inside AttributeSet objects, which are only available inside the View's constructors.

Therefore, if you cannot modify the source of the custom View class, you cannot accomplish what you're looking to do.

If you can modify the source of the class, then you can save a reference to the attribute value inside the constructor, and provide a getter method for it. For example:

private int strokeColor;

public MyCustomView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    ...

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
    this.strokeColor = a.getColor(R.styleable.MyCustomView_strokeColor, defaultColor);
    ...
    a.recycle();
}

public int getStrokeColor() {
    return strokeColor;
}

Upvotes: 2

Dmytro Ivanov
Dmytro Ivanov

Reputation: 1310

Here is official documentation how to do, exactly what you want. All you need is declare-styleable, where you could create your custom attribute for view. Then inside view, in constructor you retrive a values.

Upvotes: 0

Related Questions