Click here to Skip to main content
12,621,228 members (35,777 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

26.3K views
636 downloads
8 bookmarked
Posted

Android Edit Text with Cross Icon (x)

, 11 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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

<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)

Share

About the Author

huyletran
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.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionremove search icon Pin
Member 1053275818-Jan-14 9:10
memberMember 1053275818-Jan-14 9:10 
Questionhow can i use it? Pin
mouse71115-Aug-13 17:18
membermouse71115-Aug-13 17:18 
AnswerRe: how can i use it? Pin
huyletran15-Aug-13 23:09
memberhuyletran15-Aug-13 23:09 
GeneralRe: how can i use it? Pin
mouse71123-Oct-13 4:32
membermouse71123-Oct-13 4:32 
GeneralMy vote of 5 Pin
Ahmed Bensaid11-Aug-13 23:02
memberAhmed Bensaid11-Aug-13 23:02 
GeneralMy vote of 5 Pin
Yangyong Qin9-Aug-13 18:40
memberYangyong Qin9-Aug-13 18:40 
GeneralMy vote of 5 Pin
Yildirim Kocdag5-Aug-13 21:17
professionalYildirim Kocdag5-Aug-13 21:17 
GeneralRe: My vote of 5 Pin
huyletran6-Aug-13 0:02
memberhuyletran6-Aug-13 0: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161128.1 | Last Updated 12 Aug 2013
Article Copyright 2013 by huyletran
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid