Instantiating custom views
Now that we've seen how to set parameters on the XML layout and parse them on our custom view class, we'll see how to instantiate custom views from code as well and reuse then as much as possible from both instantiation mechanisms.
Instantiating custom views from code
On our custom view, we've created a single constructor with two parameters, a Context
and an AttributeSet
. Now, if we're creating our UI programmatically, or if by any other reason we need to instantiate our custom view by code, we need to create an additional constructor.
As we want to keep using our custom view in our XML layouts, we have to keep both constructors. To code avoid duplication, we will create some helper methods to initialize it and use them from both constructors:
public OwnCustomView(Context context) { super(context); init(DEFAULT_FILL_COLOR); } public OwnCustomView(Context context, AttributeSet attributeSet) { super(context, attributeSet...