Creating UI widgets from pure Java without XML
We can also create widgets from Java objects that are not a reference to an object in our layout. We can declare, instantiate, and set a widget's attributes, all in code, like this:
Button myButton = new Button();
The preceding code creates a new Button
by using new()
. The only warning is that the Button
has to be part of a layout before it can be shown. So, we could either get a reference to a layout element from our XML layout or create a new one, in code.
If we assume that we have a LinearLayout
in our XML with an id
property equal to linearLayout1
, we could incorporate our Button
from the earlier line of code in it, as follows:
// Get a reference to the LinearLayout LinearLayout linearLayout = (LinearLayout) ...
Get Android Programming for Beginners - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.