Use Java Code To Create Android UI Example

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

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

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

1. Use Java Code To Manipulate UI Components Steps.

  1. Create a android project, select empty activity template. This template will only create main activity java file and it’s layout xml file.
  2. Because we do not use the layout xml file, so remove below code in activity.
  3. Create a Layout component and use it as the root view use below code.
    setContentView(rootView, layoutParams);
  4. Create child component as you need such as button, eidttext, textvew etc. Set their properties as needed.
  5. Add child view components to the layout root view object use below code.
  6. If you want to set child component’s width or height, you need to translate size unit from dp to pixel. Because android screen use dp as the distance unit to adapt different device screen size. If you define the width or height in 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 translate.
    // Get Resources object.
    Resources r = getResources();
    // Get 200dp correspond px value.
    int widthInPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());

2. Java Code Create Android UI Example.

create android ui in java code

This example use a LinearLayout object as the root view, and create a EditText and Button as child view. The edit text and button is arranged in horizontal orientation. When click the button, it will check whether the input box is empty or not and popup related message at screen bottom.

This example do not need layout xml file, but it need two resource xml files. They all saved in app / res / values folder.

  1. app / res / values / strings.xml : This file contains the app name and text input hint text and button text definition.
  2. app / res / values / ids.xml : This file include id values for edittext and button.

create android ui in java code example files

2.1 Main Activity Java File.


import android.content.res.Resources;
import android.os.Bundle;
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 {

    protected void onCreate(Bundle savedInstanceState) {

        /* Comment below code because we do not want to
           use layout xml to build android ui. */

        // 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.
        // Display child view in center both horizontal and vertical.
        // Align child view in horizontal direction.
        // Create a LinearLayout parames object.
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(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.
        // Set edit text hint text.
        // Set hint text color.

        /* Because every android device's screen density is different,
           so android use dp as the width or height unit in layout xml file.
           Use dp as length unit can make UI component display and behave same in different android devices.
           But in java code editText.setWidth()'s input parameter is 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());
        // Add edittext as root view's child.

        // Create a button.
        Button button = new Button(this);
        // Set submit button id from resource file.
        // Set button text by string resource id.
        // Show button text by original character case.
        // Add button to the root view.

        // When this button is clicked.
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                // Get user input email.
                String email = editText.getText().toString();

                    // 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

    <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>

2.3 ids.xml

This xml is not exist by default, you should create it manually in app / res / values folder.


    <item name="id_edit_text" type="id" />

    <item name="id_submit_button" type="id" />

0 0 votes
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x