Android Programming In Java: Programming the UI
Written by Mike James   
Monday, 03 June 2019
Article Index
Android Programming In Java: Programming the UI
View Group
Layout Properties

To make this button a tiny bit more interesting we can customize it by setting properties. For example:

Button b = new Button(this);
b.setText("Hello Button");

If you run this you will see a button that fills the screen with the caption "Hello Button".


Don't bother setting any layout properties in code because at the moment there is no layout in force so they will be ignored. How to activate a layout is our next topic.

The ViewGroup

If an Activity can only show a single View object, how can we ever create a complex UI with multiple buttons, textViews and other components? The answer, and you probably already guessed it, is that there are Layout, or ViewGroup, objects which can be used to host other View objects.

You already know about using Layouts in the Designer or in an XML file, but they, like all UI elements, correspond to particular Java classes that does the actual work.

A ViewGroup can display multiple View objects. So in nearly all cases the View object that is associated with an Activity is a Layout View. When the Activity asks the Layout View to render itself, by calling its onDraw method, the Layout calls the onDraw method of each of the View objects it contains and puts them together to make a single result. Of course, it also performs a layout operation positioning and sizing the View objects it contains. 

So a Layout does two things:

  • it hosts other View objects

  • it performs the layout function after which it is named. 

To see this in action try: 

protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  LinearLayout linLayout=new LinearLayout(this);  Button b = new Button(this);  b.setText("Hello Button");  linLayout.addView(b);  setContentView(linLayout); }

If you run this program you will see a button at the very top left of the screen.

The first instruction creates a LinearLayout object. This is a subclass of View that can contain other View objects and it organizes them in a left to right or top to bottom way depending on the setting of its orientation property. Next we create a button object and then use the standard addView method of the LinearLayout to add it to the layout.

All Layouts have an addView method, which can be used to add multiple View objects.

You can add more buttons to see how the default LinearLayout works:

protected void onCreate(Bundle savedInstanceState) {
 LinearLayout linLayout=new LinearLayout(this);
 Button b1 = new Button(this);  b1.setText("Hello Button 1");  linLayout.addView(b1);
 Button b2 = new Button(this);  b2.setText("Hello Button 2");  linLayout.addView(b2);
 Button b3 = new Button(this);  b3.setText("Hello Button 3");  linLayout.addView(b3);  setContentView(linLayout); }




Last Updated ( Monday, 03 June 2019 )