0

I want to create a custom view a thing like a power switch ( a switch that switches between ON and OFF). When I have started to implement it I faced 3 constructors for View class:

public CusatomView(Context context) {
    super(context);
}

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

Now my question is: Which one of these constructors I should complete it to retrieve my own XML attribute (for instance: textOn and textOff)?
And what is the role of each?

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • 1
    Check this if it helps http://stackoverflow.com/questions/18681956/setting-color-of-a-paint-object-in-custom-view. Also read Professional Android DEvelopment By Reto Meier. Chapter 3. – Raghunandan Dec 14 '13 at 06:58
  • @Raghunandan thanks for your link, it's helpful – frogatto Dec 14 '13 at 07:14

2 Answers2

2

Ideally, you should do your stuff in a separate method and call this from all three constructors, because you never know which of the constructor will be called. Here are the roles:

  1. CusatomView(Context context) creates a new view with no attributes initialized.

  2. CustomView(Context context, AttributeSet attrs) is invoked when you set attributes like layout_height or layout_width in your layout.xml

  3. CustomView(Context context, AttributeSet attrs, int defStyle) is used when you set styles to your view.

Abhishek Shukla
  • 1,242
  • 8
  • 11
0

You should create another funciton init and call it in all.

public CusatomView(Context context) {
    super(context);
    init();
}

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

The thing is any of this constructors can be used to instantiate your custom view. As in when you create a view in java code you just provide context and when it is created from xml attrs is also supplied.

vipul mittal
  • 17,343
  • 3
  • 41
  • 44