Android自定义控件EditText实现清除和抖动功能
本文实例为大家分享了AndroidEditText实现清除和抖动功能的具体代码,供大家参考,具体内容如下
源码如下:
publicclassClearEditTextextendsEditTextimplementsView.OnFocusChangeListener,TextWatcher{
/
*删除按钮的引用
*/
privateDrawablemClearDrawable;
/
*控件是否有焦点
*/
privatebooleanhasFoucs;
publicClearEditText(Contextcontext){
this(context,null);
}
publicClearEditText(Contextcontext,AttributeSetattrs){
//这里构造方法也很重要,不加这个很多属性不能再XML里面定义
this(context,attrs,android.R.attr.editTextStyle);
}
publicClearEditText(Contextcontext,AttributeSetattrs,intdefStyle){
super(context,attrs,defStyle);
init();
}
privatevoidinit(){
//获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,2是获得右边的图片顺序是左上右下(0,1,2,3,)
mClearDrawable=getCompoundDrawables()[2];
if(mClearDrawable==null){
//thrownew
//NullPointerException("YoucanadddrawableRightattributeinXML");
mClearDrawable=getResources().getDrawable(R.drawable.icon_clear_input);
}
mClearDrawable.setBounds(0,0,mClearDrawable.getIntrinsicWidth(),mClearDrawable.getIntrinsicHeight());
//默认设置隐藏图标
setClearIconVisible(false);
//设置焦点改变的监听
setOnFocusChangeListener(this);
//设置输入框里面内容发生改变的监听
addTextChangedListener(this);
}
/
*因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件当我们按下的位置在EditText的宽度-
*图标到控件右边的间距-图标的宽度和EditText的宽度-图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
*/
@Override
publicbooleanonTouchEvent(MotionEventevent){
if(event.getAction()==MotionEvent.ACTION_UP){
if(getCompoundDrawables()[2]!=null){
booleantouchable=event.getX()>(getWidth()-getTotalPaddingRight())&&(event.getX()<((getWidth()-getPaddingRight())));
if(touchable){
this.setText("");
}
}
}
returnsuper.onTouchEvent(event);
}
/
*当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
*/
@Override
publicvoidonFocusChange(Viewv,booleanhasFocus){
this.hasFoucs=hasFocus;
if(hasFocus){
setClearIconVisible(getText().length()>0);
}else{
setClearIconVisible(false);
}
}
/
*设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
*
*@paramvisible
*/
protectedvoidsetClearIconVisible(booleanvisible){
Drawableright=visible?mClearDrawable:null;
setCompoundDrawables(getCompoundDrawables()[0],getCompoundDrawables()[1],right,getCompoundDrawables()[3]);
}
/
*当输入框里面内容发生变化的时候回调的方法
*/
@Override
publicvoidonTextChanged(CharSequences,intstart,intcount,intafter){
if(hasFoucs){
setClearIconVisible(s.length()>0);
}
}
@Override
publicvoidbeforeTextChanged(CharSequences,intstart,intcount,intafter){
}
@Override
publicvoidafterTextChanged(Editables){
}
/
*设置晃动动画
*/
publicvoidsetShakeAnimation(){
this.startAnimation(shakeAnimation(5));
}
/
*晃动动画
*
*@paramcounts
*1秒钟晃动多少下
*@return
*/
publicstaticAnimationshakeAnimation(intcounts){
AnimationtranslateAnimation=newTranslateAnimation(0,10,0,0);
//设置一个循环加速器,使用传入的次数就会出现摆动的效果。
translateAnimation.setInterpolator(newCycleInterpolator(counts));
translateAnimation.setDuration(500);
returntranslateAnimation;
}
}
使用方法同普通的EditText:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。