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); int fillColor; TypedArray ta =
context.getTheme().obtainStyledAttributes(attributeSet,
R.styleable.OwnCustomView, 0, 0); try { fillColor = ta.getColor(R.styleable.OwnCustomView_fillColor,
DEFAULT_FILL_COLOR); } finally { ta.recycle(); } init(fillColor); } private void init(int fillColor) { backgroundPaint = new Paint(); backgroundPaint.setStyle(Paint.Style.FILL); setFillColor(fillColor); } public void setFillColor(int fillColor) { backgroundPaint.setColor(fillColor); }
We also created a public method, setFillColor(int), so we can set the fill color by code as well. For example, let's modify our Activity to create the view hierarchy programmatically instead of inflating it from an XML layout file:
public class MainActivity extends AppCompatActivity { private static final int BRIGHT_GREEN = 0xff00ff00; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams( new LinearLayout.LayoutParams(ViewGroup.
LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)); OwnCustomView customView = new OwnCustomView(this); customView.setFillColor(BRIGHT_GREEN); linearLayout.addView(customView); setContentView(linearLayout); } }
Here, we're just creating a LinearLayout with vertical orientation and adding a custom view as a child. Then we're setting the LinearLayout as the content view of the Activity. Also, we've used a hexadecimal color directly. If we're not used to specifying colors in hexadecimal format, we could use Color.argb() or Color.rgb() to convert color components to an integer value.
The full source code can be found in the Example05-Code folder in the GitHub repository.