본문으로 건너뛰기

EditText in Android - A Beginner's Guide

If you're new to Android development, you may have heard of the EditText widget. This widget is used to get input from the user in the form of text. In this article, we'll explore how to use EditText in Android, including some code examples.

What is EditText?

EditText is a user interface widget in Android that allows users to enter and edit text. It is one of the most commonly used widgets in Android, and can be used in a variety of user interfaces, including forms, chat applications, and more.

Using EditText in Android

To use EditText in your Android application, you'll need to add the EditText widget to your layout XML file. Here's an example:

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:inputType="text" />

In this example, we've added an EditText widget to our layout file. We've given it an ID of "editText" so that we can reference it in our code. We've also set the width to "match_parent" and the height to "wrap_content", which means that the widget will take up as much width as its parent, and will adjust its height to fit its content.

We've also set the "hint" attribute to "Enter your name". This will display a hint text in the EditText widget when it is empty, prompting the user to enter their name.

Finally, we've set the "inputType" attribute to "text". This tells Android that we want the user to enter text into this widget.

Retrieving Text from EditText

Once the user has entered text into the EditText widget, we'll need to retrieve that text in our code. Here's an example:

EditText editText = findViewById(R.id.editText);
String text = editText.getText().toString();

In this example, we've first retrieved a reference to the EditText widget using its ID. We've then called the "getText" method on the EditText widget to retrieve the text that the user has entered. We've then called the "toString" method on the text to convert it to a string that we can work with.

How to Create a Searchable EditText

Basically we want a custom edittext that looks and behaves like a SearchView. This means it will have a search icon and a delete icon.

We will need to implement the OnFocusChangeListener interface, which is defined in the android.view.View class.

This then allows us to listen to the onFocusChange events:

    @Override
public void onFocusChange(View arg0, boolean hasFocus) {..}

Here's the full class:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;

public class SearchEditText extends EditText implements OnFocusChangeListener{

private static final String TAG = "SearchEditText";
/**
* Whether the icon is on the left by default
*/
private boolean isIconLeft = false;

private Drawable[] drawables; // Control image resource
private Drawable drawableLeft; // Search icon and delete button icon

public SearchEditText(Context context) {
this(context, null);
init();
}

public SearchEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

public SearchEditText(Context context, AttributeSet attrs) {
this(context, attrs,android.R.attr.editTextStyle);
init();
}

private void init() {
setOnFocusChangeListener(this);
}

@Override
public void onFocusChange(View arg0, boolean hasFocus) {
if(TextUtils.isEmpty(getText().toString()))
isIconLeft = hasFocus;
}

@Override
protected void onDraw(Canvas canvas) {
if (isIconLeft) { // If it is the default style, draw directly
this.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
super.onDraw(canvas);
} else { // If it is not the default style, you need to draw the icon in the middle
if (drawables == null) drawables = getCompoundDrawables();
if (drawableLeft == null) drawableLeft = drawables[0];
float textWidth = getPaint().measureText(getHint().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = drawableLeft.getIntrinsicWidth();
float bodyWidth = textWidth + drawableWidth + drawablePadding;
canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0);
super.onDraw(canvas);
}
}

}
2. How to Set text for EditText and adjust the cursor to the end

You, as the title suggests, want to set text to an edittext, then move the cursor to the end of the edittext. All you have to do is invoke the setSelection() method, then obtain and pass the length of the text in the edittext.

    /**
* Set text for EditText and adjust the cursor to the end
*/
public static void setTextWithSelectionAtLast(EditText editText, String text) {
editText.setText(text);
editText.setSelection(editText.getText().length());
}
3. How to Enable and Disable EditText

EditText can be enabled and disabled ondemand. This allows you to have control over when users are able to use this widget. If for whatever reason you don't want users to be able to type into an edittext, you don't have to hide the edittext. Instead you can just disable it, then enable it later.

    public static void disableEditText(EditText editText){
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
}

public static void enableEditText(EditText editText){
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
}
4. How to Check Multiple Edittexts For Emptyness

You have a bunch of edittexts you need to ensure are empty. One option is to go ahead checking them one by one, whether you have five or a hundred.

Or the second option is to create a simple helper class that receives the EditTexts as a param and loop through them.

Here's a simple reusable method to do that for us.

    /**
* Determines if all EditText views supplied are empty.
*
* @param views {@link EditText} views to be checked.
*
* @return true if all {@link EditText} views are empty, false otherwise.
*/
public static boolean isEmpty(final EditText... views) {
for (final EditText view : views) {
if (view != null) {
if (!TextUtils.isEmpty(view.getText().toString())) {
return false;
}
}
}

return true;
}

AppCompatEditText

Android AppCompatEditText Tutorial and Example.

Creating a Custom EditText

Let's say we want to create a custom AppCompatEditText called a TextBox.

We will supply a constructorand can override various events as per our wish.

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;

public class TextBox extends android.support.v7.widget.AppCompatEditText
{
Context context;

public TextBox(Context context, AttributeSet attributeSet)
{
super(context,attributeSet);
this.context = context;
}

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent keyEvent)
{
if(keyCode == KeyEvent.KEYCODE_BACK) // if back button is pressed
{
GameStandard.instance.finish();
}
return false;
}
}

TextInputEditText

Android TextInputEditText Tutorial.

This is a subclass of android.widget.EditText designed to be used as a child of android.support.design.widget.TextInputLayout.

TextInputLayout itself is important since it wraps an TextInputEditText and shows a floating label when the hint is hidden due to the user inputting text.

TextInputEditText is compatible with older versions of the platform in that it derives from AppCompatEditText.

This allows it to inherit alot of features and apis.

TextInputLayout

Android TextInputLayout Tutorial and Example

TextInputLayout is a layout that wraps android.widget.EditText to show a floating label when the hint is hidden due to the user inputting text.

This layout is normally used with android.support.design.widget.TextInputEditText.

Some of the unique features it supports include:

  • Enabling and Setting Errors via setErrorEnable(boolean) and setError(CharSequence).
  • Character counter via setCounterEnabled(boolean).

This class resides in the android.support.design.widget package.

package android.support.design.widget;

TextInputEditText inherits from LinearLayout:

public class TextInputLayout extends LinearLayout {}

TextInputLayout can only contain one EditText. Attempt to add more than one will result to java.lang.IllegalArgumentException.

Designin Android App Login Page

Let's also see a login page:


<?xml version="1.0" encoding="utf-8"?>

<ScrollView
android_layout_width="fill_parent"
android_background="@color/colorPrimary"
android_layout_height="fill_parent"
android_fitsSystemWindows="true">

<LinearLayout
android_orientation="vertical"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_paddingTop="56dp"
android_paddingLeft="24dp"
android_paddingRight="24dp">

<ImageView
android_src="@drawable/ic_local_taxi_black_24dp"
android_layout_width="72dp"
android_layout_height="72dp"
android_layout_marginBottom="24dp"
android_layout_gravity="center_horizontal" />

<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_layout_marginTop="8dp"
android_layout_marginBottom="8dp">
<EditText android_id="@+id/input_email"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_inputType="textEmailAddress"
android_textColor="#ffffff"
android_hint="Email" />
</android.support.design.widget.TextInputLayout>

<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_layout_marginTop="8dp"
android_layout_marginBottom="8dp">
<EditText android_id="@+id/input_password"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_inputType="textPassword"
android_textColor="#ffffff"
android_hint="Password"/>
</android.support.design.widget.TextInputLayout>

<android.support.v7.widget.AppCompatButton
android_id="@+id/btn_login"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_layout_marginTop="24dp"
android_layout_marginBottom="24dp"
android_background="@color/colorPrimaryDark"
android_padding="12dp"
android_textColor="#ffffff"
android_text="Login"/>

<TextView android_id="@+id/link_signup"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_layout_marginBottom="24dp"
android_textColor="#ffffff"
android_text="No account yet? Create one"
android_gravity="center"
android_textSize="16dip"/>

</LinearLayout>
</ScrollView>

Conclusion

EditText is a powerful widget in Android that allows users to input and edit text. By using EditText in your Android application, you can create user interfaces that are more interactive and engaging. With the examples provided in this article, you should now be ready to start using EditText in your own Android applications.