Skip to content

Creating UI elements with Java

The Android framework provides you with a set of classes that you can use to define layouts and widgets programmatically. The advantages of defining the interface this way are that you have total control over the configuration of each element, and you are using Java as the single development language throughout the app. Let's say that you want a layout with a text field at the top left and an action button at the bottom right. You could create this interface with a RelativeLayout as shown in Figure 8.

public class MainActivity extends AppCompatActivity {

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RelativeLayout rLayout = new RelativeLayout(this);
    rLayout.setLayoutParams(new LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT));

    TextView tView = new TextView(this);
    tView.setText("Hello, World!");

    RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    textParams.leftMargin = 20;
    textParams.topMargin = 20;
    rLayout.addView(tView, textParams);

    FloatingActionButton fab = (new FloatingActionButton(this));
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();
        }
    });

    RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    buttonParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    buttonParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    buttonParams.rightMargin = 100;
    buttonParams.bottomMargin = 100;
    rLayout.addView(fab, buttonParams);

    setContentView(rLayout);
}

Figure 8: Creating UI elements programmatically

A major disadvantage of creating your UI by directly instantiating Java classes are that your presentation code can easily get mixed up with your behavioural code which can make debugging very difficult. The second major disadvantage of this approach is the sheer amount of code that needs to be written for very small gains.

Fortunately using declarative XML layouts solves both of these problems...