Android实现仿IOS带清空功能的文本输入框
/** *@类名:ClearableEditText *@功能描述: *@作者:WilliamXu *@创建日期:2013-4-13 *@修改人: *@修改日期: *@修改备注: *@版本号:1.0 */ publicclassClearableEditTextextendsEditTextimplements OnFocusChangeListener,TextWatcher{ privateDrawablexD; publicClearableEditText(Contextcontext){ super(context); init(); } publicClearableEditText(Contextcontext,AttributeSetattrs){ super(context,attrs); init(); } publicClearableEditText(Contextcontext,AttributeSetattrs,intdefStyle){ super(context,attrs,defStyle); init(); } privatevoidinit(){ xD=getCompoundDrawables()[2]; if(xD==null){ xD=getResources() .getDrawable(R.drawable.search_clear); } xD.setBounds(0,0,xD.getIntrinsicWidth(),xD.getIntrinsicHeight()); setClearIconVisible(false); super.setOnFocusChangeListener(this); addTextChangedListener(this); } @Override publicvoidsetOnFocusChangeListener(OnFocusChangeListenerf){ this.f=f; } privateOnFocusChangeListenerf; @Override publicbooleanonTouchEvent(MotionEventevent){ if(getCompoundDrawables()[2]!=null){ if(event.getAction()==MotionEvent.ACTION_UP){ booleantappedX=event.getX()>(getWidth() -getPaddingRight()-xD.getIntrinsicWidth()); if(tappedX){ setText(""); event.setAction(MotionEvent.ACTION_CANCEL); } } } returnsuper.onTouchEvent(event); } @Override publicvoidonFocusChange(Viewv,booleanhasFocus){ if(hasFocus){ setClearIconVisible(getText().length()>0); }else{ setClearIconVisible(false); } if(f!=null){ f.onFocusChange(v,hasFocus); } } protectedvoidsetClearIconVisible(booleanvisible){ Drawablex=visible?xD:null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1],x,getCompoundDrawables()[3]); } @Override publicvoidonTextChanged(CharSequences,intstart,intcount, intafter){ setClearIconVisible(s.length()>0); } @Override publicvoidbeforeTextChanged(CharSequences,intstart,intcount, intafter){ //TODOAuto-generatedmethodstub } @Override publicvoidafterTextChanged(Editables){ //TODOAuto-generatedmethodstub } } 本文转自william_xu 51CTO博客,原文链接:http://blog.51cto.com/williamx/1195051,如需转载请自行联系原作者