Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Android Edit Text with Cross Icon (x)

4.88/5 (9 votes)
11 Aug 2013CPOL 43.2K   682  
Make edit text with specified length, delete icon

Introduction

It is maybe a simple custom only. :) But I will post for the amateur Android coder like me.

In fact, you may have got requirements for an edit text like below:

  • There is a Search icon at the beginning of your edit text.
  • When inserting text, the [X] icon will display. If you tap on the [X] icon, it will delete all input text.
  • The max length is 10 characters.

The sample given below will resolve it.

Using the Code

MyEditText.java

Java
public class MyEditText extends EditText {
    private static final int MAX_LENGTH = 10;

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            this.setBackgroundResource(android.R.drawable.edit_text);
        }

        setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public synchronized boolean onEditorAction(TextView v,
                    int actionId, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    return true;
                }
                return false;
            }
        });

        String value = "";
        final String viewMode = "editing";
        final String viewSide = "right";
        final Drawable x = getResources().getDrawable(R.drawable.delete_icon);

        // The height will be set the same with [X] icon
        setHeight(x.getBounds().height());

        x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
        Drawable x2 = viewMode.equals("never") ? null : viewMode
                .equals("always") ? x : viewMode.equals("editing") ? (value
                .equals("") ? null : x)
                : viewMode.equals("unlessEditing") ? (value.equals("") ? x
                        : null) : null;
        // Display search icon in text field
        final Drawable searchIcon = getResources().getDrawable(
                android.R.drawable.ic_search_category_default);
        searchIcon.setBounds(0, 0, x.getIntrinsicWidth(),
                x.getIntrinsicHeight());

        setCompoundDrawables(searchIcon, null, viewSide.equals("right") ? x2
                : null, null);

        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getCompoundDrawables()[viewSide.equals("left") ? 0 : 2] == null) {
                    return false;
                }
                if (event.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                // x pressed
                if ((viewSide.equals("left") && event.getX() < getPaddingLeft()
                        + x.getIntrinsicWidth())
                        || (viewSide.equals("right") && event.getX() > getWidth()
                                - getPaddingRight() - x.getIntrinsicWidth())) {
                    Drawable x3 = viewMode.equals("never") ? null : viewMode
                            .equals("always") ? x
                            : viewMode.equals("editing") ? null : viewMode
                                    .equals("unlessEditing") ? x : null;
                    setText("");
                    setCompoundDrawables(searchIcon, null,
                            viewSide.equals("right") ? x3 : null, null);
                }
                return false;
            }
        });
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                Drawable x4 = viewMode.equals("never") ? null : viewMode
                        .equals("always") ? x
                        : viewMode.equals("editing") ? (getText().toString()
                                .equals("") ? null : x) : viewMode
                                .equals("unlessEditing") ? (getText()
                                .toString().equals("") ? x : null) : null;
                setCompoundDrawables(searchIcon, null,
                        viewSide.equals("right") ? x4 : null, null);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.length() > MAX_LENGTH) {
                    setText(s.subSequence(0, MAX_LENGTH));
                    setSelection(MAX_LENGTH);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }
        });
    }
}

main_activity.xml

XML
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <com.example.myedittext.MyEditText
        android:layout_width="300dp"
        android:layout_height="wrap_content" />

</RelativeLayout>   

You must create delete_icon.png in resource, as [X] icon, of course.

I added the result:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)