Reputation: 29287
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?
Upvotes: 0
Views: 1831
Reputation: 17401
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.
Upvotes: 0
Reputation: 1242
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:
CusatomView(Context context)
creates a new view with no attributes initialized.
CustomView(Context context, AttributeSet attrs)
is invoked when you set attributes like layout_height
or layout_width
in your layout.xml
CustomView(Context context, AttributeSet attrs, int defStyle)
is used when you set styles to your view.
Upvotes: 2