Android EditText

| Page Views: 287

Android EditText Tutorial and Examples.

In this session we look at one of the most usable and needed widgets, the EditText class. We look at several short as well as full examples and classes associated with it.

What is EditText?

EditText is an android framework widget that allows us input text data into applications.

Why EditText?

The mere ability to input data makes edittext one of the really most important widgets. How will users even be able to use many apps if they cannot type inputs into the app? Think of applications like messaging apps, email apps, event the phone dialer where you need to type the phone number to dial.EditText is the primary class that provides this ability. In fact even search widgets are constructed from edittext.

Computers are known to be information processing devices. Unlike devices like Radio and Television, computers are able to obtain a diversity of raw inputs from users and process them. Users can type data into computers and chances are that they are going to be using EditText class or it's derivation like SearchView.

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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post