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) 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 and then all the widgets we want to add, and finally calling...