Use Java Code To Create Android UI Example

Create and manage android UI components in java source code can be used in the below scenario.

  1. When you want to add or remove UI components dynamically by the different conditions at run-time.
  2. When the layout XML file is too huge, it is not efficient to load so many UI components from the layout XML file.

This article will show you examples of how to use java code to manipulate android UI components.

1. Use Java Code To Manipulate UI Components Steps.

  1. Create an android project, select the Empty Activity template. This template will only create the main activity java file and a layout XML file.
  2. Because we do not use the layout XML file, so remove the below code in the android activity.
    setContentView(R.layout.activity_main);
  3. Create a Layout component and use it as the root view use the below code.
    setContentView(rootView, layoutParams);
  4. Create child components as you need such as Button, EditText, TextView, etc. Set their properties as needed.
  5. Add child view components to the layout root view object use the below code.
    rootView.addView(editText);
  6. If you want to set the child component’s width or height, you need to translate the size unit from dp to pixel, because the android screen uses dp as the distance unit to adapt different device screen sizes.
  7. If you define the width or height in the layout XML file then the unit is dp by default. But in java code, the input parameter for the setWidth() or setHeight() method is pixel. So need to translate them use the below source code.
    // Get Resources object.
    Resources r = getResources();
    // Get 200dp correspond px value.
    int widthInPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());
    editText.setWidth(widthInPx);

2. Java Code Create Android UI Example.

  1. Below is the example screen in the android emulator.
    create-android-ui-in-java-code
  2. This example uses a LinearLayout object as the root view and creates an EditText and Button as a child view. The edit text and button are arranged in horizontal orientation.
  3. When clicking the button, it will check whether the input box is empty or not and pop up related messages at the screen bottom.
  4. This example does not need a layout XML file, but it needs two resource XML files. They are all saved in the app/res/values folder.
  5. app / res / values / strings.xml: This file contains the app name and text input hint text and button text definition.
  6. app / res / values / ids.xml: This file include id values for edittext and button.
  7. Below is the example project source files list.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\ANDROIDUIINJAVACODE
    │   .gitignore
    │   build.gradle
    │   gradle.properties
    │   gradlew
    │   gradlew.bat
    │   settings.gradle
    │
    ├───.idea
    │       gradle.xml
    │       misc.xml
    │       modules.xml
    │       runConfigurations.xml
    │
    ├───app
    │   │   .gitignore
    │   │   build.gradle
    │   │   proguard-rules.pro
    │   │
    │   └───src
    │       ├───androidTest
    │       │   └───java
    │       │       └───com
    │       │           └───dev2qa
    │       │               └───android
    │       │                   └───example
    │       │                       └───myapplication
    │       │                               ExampleInstrumentedTest.java
    │       │
    │       ├───main
    │       │   │   AndroidManifest.xml
    │       │   │
    │       │   ├───java
    │       │   │   └───com
    │       │   │       └───dev2qa
    │       │   │           └───android
    │       │   │               └───example
    │       │   │                   └───myapplication
    │       │   │                           MainActivity.java
    │       │   │
    │       │   └───res
    │       │       ├───drawable
    │       │       │       ic_launcher_background.xml
    │       │       │
    │       │       ├───drawable-v24
    │       │       │       ic_launcher_foreground.xml
    │       │       │
    │       │       ├───layout
    │       │       │       activity_main.xml
    │       │       │
    │       │       ├───mipmap-anydpi-v26
    │       │       │       ic_launcher.xml
    │       │       │       ic_launcher_round.xml
    │       │       │
    │       │       ├───mipmap-hdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-mdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       └───values
    │       │               colors.xml
    │       │               ids.xml
    │       │               strings.xml
    │       │               styles.xml
    │       │
    │       └───test
    │           └───java
    │               └───com
    │                   └───dev2qa
    │                       └───android
    │                           └───example
    │                               └───myapplication
    │                                       ExampleUnitTest.java
    │
    └───gradle
        └───wrapper
                gradle-wrapper.jar
                gradle-wrapper.properties

2.1 Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.android.example.myapplication;
    
    import android.content.res.Resources;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.TypedValue;
    import android.view.Gravity;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            /* Comment below code because we do not want to
               use layout xml to build android ui. */
            //setContentView(R.layout.activity_main);
    
            // We use a LinearLayout object as the root view object.
            LinearLayout rootView = new LinearLayout(this);
            // Set root view properties such as background color, gravity and orientation.
            rootView.setBackgroundColor(Color.GREEN);
            // Display child view in center both horizontal and vertical.
            rootView.setGravity(Gravity.CENTER);
            // Align child view in horizontal direction.
            rootView.setOrientation(LinearLayout.HORIZONTAL);
            // Create a LinearLayout parames object.
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(10,10, 10,10);
    
            // Use LinearLayout object as root view
            setContentView(rootView, layoutParams);
    
    
            // Create a EditText ui component.
            final EditText editText = new EditText(this);
            // Set editText id from ids.xml resource file.
            editText.setId(R.id.id_edit_text);
            // Set edit text hint text.
            editText.setHint(R.string.edit_text_hint);
            // Set hint text color.
            editText.setHintTextColor(Color.BLUE);
    
            /* Because every android device's screen density is different,
               so android uses dp as the width or height unit in the layout XML file.
               Use dp as a length unit can make UI components display and behave the same in different android devices.
               But in java code editText.setWidth()'s input parameter is the pixel,
               so we need to translate dp to pixel first. */
    
            // Get Resources object.
            Resources r = getResources();
            // Get 200dp correspond px value.
            int widthInPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());
            editText.setWidth(widthInPx);
            // Add edittext as root view's child.
            rootView.addView(editText);
    
            // Create a button.
            Button button = new Button(this);
            // Set submit button id from resource file.
            button.setId(R.id.id_submit_button);
            // Set button text by string resource id.
            button.setText(R.string.submit_button_text);
            // Show button text by original character case.
            button.setAllCaps(false);
            // Add button to the root view.
            rootView.addView(button);
    
            // When this button is clicked.
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Get user input email.
                    String email = editText.getText().toString();
    
                    if(TextUtils.isEmpty(email))
                    {
                        // If email is empty.
                        Toast.makeText(getApplicationContext(), "Email can not be empty.", Toast.LENGTH_LONG).show();
                    }else {
                        // If email is not empty.
                        Toast.makeText(getApplicationContext(), "Your email has been submitted.", Toast.LENGTH_LONG).show();
                    }
                }
            });
    
        }
    }

2.2 strings.xml

  1. strings.xml.
    <resources>
        <string name="app_name">Build Android UI Use Java Code</string>
    
        <string name="edit_text_hint">Input email here...</string>
    
        <string name="submit_button_text">Submit</string>
    </resources>

2.3 ids.xml

  1. This XML is not existed by default, you should create it manually in the app/res/values folder.
    <resources>
    
        <item name="id_edit_text" type="id" />
    
        <item name="id_submit_button" type="id" />
    
    </resources>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky