Custom components ------ EditText with deletion function, ------ edittext

Source: Internet
Author: User

Custom components ------ EditText with deletion function, ------ edittext

In the past, FrameLayout was often used to add the icon on the left and a delete button on the Right of EditText. In this case, code reuse is poor and maintenance is also troublesome. The best way is to rewrite EditText to implement this function. Now let's take a look at the implementation method later.

The rewritten component has the following functions. The delete button appears only when the EditText content is not empty and the focus is obtained. Click the delete button to clear the content. The Code is as follows:

Public class CleanableEditText extends EditText {// callback function private TextWatcherCallBack mCallback; // Delete the icon private Drawable mDrawable; private Context mContext; public void setCallBack (TextWatcherCallBack mCallback) {this. mCallback = mCallback;} public CleanableEditText (Context context) {super (context); this. mContext = context; init ();} public CleanableEditText (Context context, AttributeSet attrs) {super (conte Xt, attrs); this. mContext = context; init ();} public CleanableEditText (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); this. mContext = context; init ();} public void init () {mDrawable = mContext. getResources (). getDrawable (R. drawable. ic_clear); mCallback = null; // overwrites TextWatcher, which is not implemented by every method in actual implementation. reduces the amount of code TextWatcher textWatcher = new TextWatcherAdapter () {@ Overridepublic voi D afterTextChanged (Editable s) {// Update Status, check whether the delete button updateCleanable (length (), true) is displayed; // If a callback is set in the activity, then, if (mCallback! = Null) mCallback. handleMoreTextChanged () ;}}; this. addTextChangedListener (textWatcher); this. setOnFocusChangeListener (new OnFocusChangeListener () {@ Overridepublic void onFocusChange (View v, boolean hasFocus) {// Update Status, check whether the delete button updateCleanable (length () is displayed (), hasFocus) ;}}) ;}// when the content is not empty and the focus is obtained, the delete button on the right is displayed. public void updateCleanable (int length, boolean hasFocus) {if (length ()> 0 & hasFocus) setCompoundDrawablesWithIn TrinsicBounds (null, null, mDrawable, null); Round (null, null, null);} @ Overridepublic boolean onTouchEvent (MotionEvent event) {final int DRAWABLE_RIGHT = 2; // you can obtain the top, bottom, left, and right drawable, and the second row on the right. If the icon is not set, it is null. Drawable rightIcon = getCompoundDrawables () [DRAWABLE_RIGHT]; if (rightIcon! = Null & event. getAction () = MotionEvent. ACTION_UP) {// check whether the clicked position is the delete icon on the right. // note that getRwwX () is used to obtain the position relative to the screen. getX () it is possible to obtain the relative position of the parent component int leftEdgeOfRightDrawable = getRight ()-getPaddingRight ()-rightIcon. getBounds (). width (); if (event. getRawX ()> = leftEdgeOfRightDrawable) {setText ("") ;}} return super. onTouchEvent (event) ;}@ Overrideprotected void finalize () throws Throwable {mDrawable = null; super. finalize ();}}

There are two key points for implementation. One of them is that there is an API that can set up or down icons for EditText. Therefore, this avoids the clumsy method of FrameLayout (the icon on the right is automatically added to the component code, and the icon on the left must be declared in the XML Code ). Note that you must know how to calculate the location of click events,


A small problem encountered during implementation. In the onTouchEvent () method, if an event is consumed (true or false is returned based on the situation), a problem occurs. You can click EditText, if you set log output, you can find that action_down, action_move, and action_up are all output, indicating that the click event is normal, but the focus is still unavailable. It is not difficult to guess that the focus of EditText may be related to the click event. If the requestFocus () method is forcibly called, the problem can be solved. However, there is instability and sometimes a bug occurs. The cause is not detailed yet. Therefore, I will not process the click event here and directly return super. onTouchEvent (event)


Several tips are used for coding.

1. When addTextChangedListener is used, it is often necessary to implement three methods. However, we only need to rewrite one method, so the code is somewhat redundant. The solution is to add an adapter.

2. addTextChangedListener has been added here. If I need to listen in the activity, if I want to listen directly, it will overwrite the listening in CleanableEditText. To solve this problem, I used a callback interface so that users can choose to do more in addTextChangedListener. The implementation method is as follows:

The code for the callback interface is as follows:

public interface TextWatcherCallBack {public void handleMoreTextChanged();}

The activity needs to implement TextWatcherCallBack and set callback for CleanableEditText (for example, the last two sentences of the following code)


public class LoginActivity extends BaseActivity implements TextWatcherCallBack {private ClearableAutoCompleteTextView accountView;private CleanableEditText passwordText;private Button login;@Overrideprotected void onCreate(Bundle bundle) {super.onCreate(bundle);setContentView(R.layout.activity_login);accountView = (ClearableAutoCompleteTextView) findViewById(R.id.et_account);passwordText = (CleanableEditText) findViewById(R.id.et_password);login = (Button) findViewById(R.id.bt_login);accountView.setCallBack(this);passwordText.setCallBack(this);//,,,,,,,}}


The usage of this custom component is written here and is now used by one of my XMPP Instant Messaging Tools hosted on Github.

Portal: Github address

The master branch is the code written in android at the beginning. It is very poor and I cannot see it myself. However, the only value is that I can refer to the smack API now, at that time, I also wrote android beginners. The develop branch was hard to write again, and the login interface was just rolled out tonight. In my spare time, I will mainly maintain this project and try to use more android knowledge. And write a blog to record this knowledge. Welcome to fork. Welcome to issue.







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.