frogatto
frogatto

Reputation: 29287

Android - Create Custom View

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

Answers (2)

vipul mittal
vipul mittal

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

Abhishek Shukla
Abhishek Shukla

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:

  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.

Upvotes: 2

Related Questions