EditText Tutorial With Example In Android Studio (Kotlin/Java)

How-to-create-Android-EditText.png

24th February, 2023

Android EditText is a type of User Interface that allow the user to enter or modify text. Its parent class is TextView, so it inherits all the features of the Android TextView class. It helps the user to interact with the application. EditText is widely used in form screen type. Like user profile, login, sign up, feedback screen.

1. How to Create/Add EditText in Android Studio?

We can create/add Android EditText in two ways:

1.1 Create/Add EditText in XML layout file

In Android Studio, open the XML layout file, go to the palette and select EditText, add it to the layout.

Add-Android-EditText-to-layout-.gif
XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <EditText
        android:id="@+id/editTextTextPersonName6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

</LinearLayout>

1.2 Create EditText Programmatically in Android

To create a EditText programmatically using Kotlin/ Java file, simply create a object of the EditText by passing a context as parameter. See the code below.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloedittext

import android.os.Bundle
import android.text.InputType
import android.widget.EditText
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val linearLayout = findViewById<LinearLayout>(R.id.linearlayout12)

        //create editText
        val editText = EditText(this)
        editText.inputType = InputType.TYPE_TEXT_VARIATION_PERSON_NAME
        editText.setText("James")

        //add editText to the layout
        linearLayout.addView(editText)
    }
}
package com.androidchunk.helloedittext;

import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout linearLayout= findViewById(R.id.linearlayout12);

        //create editText
        EditText editText = new EditText(this);
        editText.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
        editText.setText("James");

        //add editText to the layout
        linearLayout.addView(editText);
    }
}

2. How to Get Text from Android EditText?

In Android we can get the text from the ExitText using the getText() method.

KotlinJava
content_copy light_mode remove
//instance of nameEditText
val nameEditText = findViewById<EditText>(R.id.nameEditText)

//get text from editText
val name = nameEditText.text.toString()

//toast that displays the name
Toast.makeText(this, name, Toast.LENGTH_SHORT).show()
//instance of nameEditText
EditText nameEditText = findViewById(R.id.nameEditText);

//get text from editText
String name = nameEditText.getText().toString();

//toast that displays the name
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();

Similarly, the setText(“sometext”) method is used to set text to the EditText.

KotlinJava
content_copy light_mode remove
//instance of editText
val countryEditText = findViewById<EditText>(R.id.countryEditText)

//set text to editText
countryEditText.setText("USA")
//instance of editText
EditText countryEditText = findViewById(R.id.countryEditText);

//set text to editText
countryEditText.setText("USA");

3. EditText Attributes

Let’s take a quick look at some frequently used attributes of Android editText.

Attribute Description
android:id It is used to set uniquely identify the view
android:width It sets the width of the view
android:height It sets the height of the view
android:minWidth Makes the edittext at least this pixel wide
android:minHeight Makes the edittext at least this pixel tall
android:maxWidth This makes the editText a maximum of this many pixels wide
android:maxHeight This makes the editText a maximum of this many pixels tall
android:hint This is the placeholder text that is displayed when the EditText is empty
android:inputType The type of the text being placed in editText. For example, person name, password, email, number, phone, etc.
android:text It sets text to the editText
android:textColor It is used to set the text color of editText
android:textColorHint It is used to set the hint text color of editText
android:textAllCaps It is used to present the text in all CAPS
android:fontFamily It is used to specify the font family of editText
android:textColorHighlight It is used to change the color of text selection highlight
android:gravity It is used to align the text. Like left, right, center
android:editable If we set false, the user will not be able to enter or modify the text
android:ems It is used to make the editText be exactly this many ems wide

4. EditText Methods

Some useful Android EditText Methods listed below.

Method Description
setText(CharSequence text) Sets the text in the editText
getText() Gets the text from the editText
selectAll() It is used to select entire text of the EditText
setSelection(int index) It is used to move the cursor to the position of index
setSelection(int start, int stop) Select sub-text fron 'start' to 'stop'
extendSelection(int index) Select sub-text from current cursor position to position of index

5. Android EditText Example

We have created a simple login form screen using EditText where the user has to type username and password. Let’s have a fun.

Step 5.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 5.2: Enable View Binding

In this example we are using Android Jetpack’s feature view binding.

Groovy
content_copy light_mode remove
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    ...
    ...

    buildFeatures {
        viewBinding = true
    }
    ...
    ...
}

dependencies {
    ...
    ...
    ...
}

Step 5.3: Add EditText to the XML Layout (UI)

Open the activity’s xml layout file and write the code as shown below. Here We have taken two editTexts with different inputType attributes.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:src="@mipmap/ic_launcher" />

    <EditText
        android:id="@+id/usernameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:ems="10"
        android:hint="Enter username"
        android:inputType="textPersonName"
        android:maxLength="15" />

    <EditText
        android:id="@+id/passEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:ems="10"
        android:hint="Enter password"
        android:inputType="numberPassword"
        android:maxLength="15" />

    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:text="Login" />

</LinearLayout>
//instance of editText
EditText countryEditText = findViewById(R.id.countryEditText);

//set text to editText
countryEditText.setText("USA");

Step 5.4: Update Activity File

Now navigate to the Kotlin/Java activity file and add a submit button click event listener. We have created a simple method called loginUser() that checks the validity of the editTexts and displays the appropriate result as a toast. See the code below.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloedittext

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.androidchunk.helloedittext.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    //view binding
    private lateinit var binding: ActivityMainBinding
    
    //temp user data
    private val myUserName = "user123"
    private val myPassword = "123456"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //login button click listener
        binding.loginButton.setOnClickListener(View.OnClickListener { loginUser() })
    }

    private fun loginUser() {
        //get text from username and password edittext
        val username: String = binding.usernameEditText.text.toString()
        val pass: String = binding.passEditText.text.toString()

        //simple edittext validation
        if (username.isNotEmpty() && pass.isNotEmpty()) {
            //check data
            if (username.equals(myUserName, ignoreCase = true) && pass.equals(myPassword,ignoreCase = true)) {
                Toast.makeText(this, "Login successfully", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Invalid username or password", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "You must fill in all the fields", Toast.LENGTH_SHORT).show()
        }
    }
}
package com.androidchunk.helloedittext;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.androidchunk.helloedittext.databinding.ActivityMainBinding;

class MainActivity extends AppCompatActivity {
    //view binding
    private ActivityMainBinding binding;
    
    //temp user data
    private String myUserName = "user123";
    private String myPassword = "123456";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //login button click listener
        binding.loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginUser();
            }
        });
    }

    private void loginUser() {
        //get text from username and password edittext
        String username = binding.usernameEditText.getText().toString();
        String pass = binding.passEditText.getText().toString();

        //simple edittext validation
        if (!username.isEmpty() && !pass.isEmpty()){
            //check data
            if (username.equalsIgnoreCase(myUserName) && pass.equalsIgnoreCase(myPassword)) {
                Toast.makeText(this, "Login successfully", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "Invalid username or password", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(this, "You must fill in all the fields", Toast.LENGTH_SHORT).show();
        }
    }
}

Run the application and check the output.

Step 5.5: Output

Happy coding!

Leave a Reply