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, as follows:
Button myButton = new Button();
The preceding code creates a new Button
by using the new()
keyword. The only caveat is that the Button
has to be part of a layout before it can be seen by the user. 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 put our Button
from the earlier line of code into it, as follows:
// Get a reference to the LinearLayout LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout); // Add our Button to it linearLayout.addView(myButton);
We could even create an entire layout in pure Java code by, first, creating a new layout...