Click here to Skip to main content
15,878,871 members
Articles / Mobile Apps / Android
Tip/Trick

Android Edit Text with Cross Icon (x)

Rate me:
Please Sign up or sign in to vote.
4.88/5 (9 votes)
11 Aug 2013CPOL 42.1K   682   8   8
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)


Written By
Vietnam Vietnam
I'm Java developer.
I started Java web coding from 2007 to 2010. After that, I began to develop Android from 2010 to now.
In my thinking, sharing and connecting is the best way to develop.
I would like to study more via yours comments and would like to have relationship with more developers in the world.

Comments and Discussions

 
Questionremove search icon Pin
Member 1053275818-Jan-14 8:10
Member 1053275818-Jan-14 8:10 
Questionhow can i use it? Pin
mouse71115-Aug-13 16:18
mouse71115-Aug-13 16:18 
AnswerRe: how can i use it? Pin
huyletran15-Aug-13 22:09
huyletran15-Aug-13 22:09 
GeneralRe: how can i use it? Pin
mouse71123-Oct-13 3:32
mouse71123-Oct-13 3:32 
GeneralMy vote of 5 Pin
Ahmed Bensaid11-Aug-13 22:02
professionalAhmed Bensaid11-Aug-13 22:02 
GeneralMy vote of 5 Pin
Yangyong Qin9-Aug-13 17:40
Yangyong Qin9-Aug-13 17:40 
GeneralMy vote of 5 Pin
Yildirim Kocdag5-Aug-13 20:17
Yildirim Kocdag5-Aug-13 20:17 
GeneralRe: My vote of 5 Pin
huyletran5-Aug-13 23:02
huyletran5-Aug-13 23:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.