1

I have custom attributes set in attrs.xml name custom_values, one of which is named stageNumber. I have a Button with this custom value defined e.g. custom:stageNumber="2" with an onClick handler titled goToStage. In the goToStage method I need to obtain the value of stageNumber. I am unable to fetch the AttributeSet required by the method obtainStyledAttributes.

public void goToStage(View view) {
    AttributeSet attrs = ???;
    TypedArray ta = view.getContext().obtainStyledAttributes(attrs, R.attr.custom_values);
    int stageNumber = ta.getInt(R.styleable.custom_values_stageNumber, 0);
    // do something with stageNumber
}

Any suggestions to resolve this?

voncox
  • 1,191
  • 7
  • 13

1 Answers1

3

You can access view's attributes only during inflating process either from view's constructor or from layoutInflator which inflating view with custom attributes. There is no way to access view's attributes later.

Leonidos
  • 10,482
  • 2
  • 28
  • 37
  • OK thanks. Do you know if there is another way to obtain the styled attributes in this handler method? – voncox Jan 17 '13 at 17:47
  • You can't. [Create custom button class and save attribute value while constructing](http://stackoverflow.com/questions/3441396/defining-custom-attrs). Or find another way to pass stageNumber to your handler method withour using view's attributes. – Leonidos Jan 17 '13 at 17:56
  • Creating a custom button class option means that the value of the custom attribute can be fetched but in the onClick event it will not be set. A member variable can be set the the initial value in the constructor but what if the value is changed by code elsewhere? – voncox Jan 17 '13 at 18:42
  • Why's that? Make private var to store value and create getter. So no one can change it. And you read this value later in onClickListener via that getter. – Leonidos Jan 17 '13 at 19:03