Create the RelativeLayout, Button, and Listener Programmatically

This app creates the same RelativeLayout and Button as the activity_main.xml of Click Listener. But this time the objects are created by Java, not by an .xml file. Our activity_main.xml is ignored and could have been deleted from this project. The advantage of creating the user interface programmatically is that we can have if statements that do different things under different conditions.

The first argument of the constructor RelativeLayout, the constructor Button, and the method Toast.makeText must be a Context object. Fortunately, our Activity object is a Context object.

Source code in Programmatic.zip

  1. MainActivity.java creates the RelativeLayout and the Button. Don’t forget to call addView. It also creates the listener. I commented out the first call to setContentView (which was written by Android Studio) and replaced it with a call to another method with the same name.

  2. activity_main.xml: unused and ignored, because we commented out the setContentView(R.layout.activity_main) in onCreate.

  3. strings.xml

  4. dimens.xml. This file is created automatically by Android Studio and contains dimension resources. Integers representing these values appear in R.java.

  5. R.java

  6. AndroidManifest.xml

  7. build.gradle (Module: app)

Things to try

  1. Instead of writing the three strings "Press in case of emergency.", etc., in MainActivity.java, write them as string resources in strings.xml.
        <string name="button_text">Press in case of emergency.</string>
    
            button.setText(R.string.button_text);