1

This is a custom view

public class MyView extends Button {
    private static int color;

    . . . 
}

This XML instantiates MyView several times

<LinearLayout . . .>

    <com.example.test.MyView . . . />
    <com.example.test.MyView . . . />
    <com.example.test.MyView . . . />
    <com.example.test.MyView . . . />
    <com.example.test.MyView . . . />
    <com.example.test.MyView . . . />

</LinearLayout>

I want to know what is the proper way to initialize the static color from XML.
I know already one solution (but I wonder if there is a different recommended way):

  • Define a custom attribute
<declare-stylable name=MyView>
    <attr name="color" format="integer" />
</declare-stylable>
  • Use the custom attribute on the instantiation of any MyView
<com.example.test.MyView
    app:color="@color/red"
    . . ./>
  • Set the static field during MyView constructor

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int c = a.getInteger(R.styleable.MyView_color, -1);
if( c != -1 ) color = c;

The only thing that I don't like about this solution is that it is dependent on a MyView instantiation, usually, in code, static fields and methods can be accessed independently, so I would like to know if there is a way I can set the static field also independently of the MyView actual instantitations.

ilomambo
  • 8,290
  • 12
  • 57
  • 106
  • I know of no way to set a static variable in a custom view (or any view for that matter) using XML. I would be surprised if there is. – britzl May 08 '13 at 06:21

0 Answers0