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.
    setContentView(R.layout.activity_main);
  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.
    rootView.addView(editText);
  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());
    editText.setWidth(widthInPx);

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.

READ :   Android Analog, Digital And Text Clock Example

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.

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 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());
        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

<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

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

<resources>

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

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

</resources>
(Visited 171 times, 1 visits today)

Leave a Reply

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.