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?

2
  • 1
    Check this if it helps stackoverflow.com/questions/18681956/…. Also read Professional Android DEvelopment By Reto Meier. Chapter 3. Commented Dec 14, 2013 at 6:58
  • @Raghunandan thanks for your link, it's helpful Commented Dec 14, 2013 at 7:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.