java 带清空功能的的EditText
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 带清空功能的的EditText相关的知识,希望对你有一定的参考价值。
package com.junyun.tinystore.widget;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
import com.junyun.tinystore.R;
public class ClearableEditText extends EditText implements TextWatcher {
private Drawable mClearDrawable, mClearDrawableLeft;
private Drawable drawable = null;
public ClearableEditText ( Context context, AttributeSet attrs ) {
super ( context, attrs );
mClearDrawable = getCompoundDrawables ( )[ 2 ];
if ( mClearDrawable == null ) {
mClearDrawable = context.getResources ( ).getDrawable ( R.drawable.icon_login_username_clear );
}
mClearDrawable.setBounds ( 0, 0, mClearDrawable.getIntrinsicWidth ( ),
mClearDrawable.getIntrinsicHeight ( ) );
setClearIconVisible ( false );
addTextChangedListener ( this );
}
private void setClearIconVisible ( boolean visible ) {
// 判断是否需要隐藏
if ( visible ) {
mClearDrawableLeft = getResources ( ).getDrawable (
R.drawable.icon_login_username_clear );
drawable = mClearDrawable;
} else {
mClearDrawableLeft = getResources ( ).getDrawable (
R.drawable.icon_login_username_clear );
drawable = null;
}
mClearDrawableLeft.setBounds ( 0, 0,
mClearDrawableLeft.getIntrinsicWidth ( ),
mClearDrawableLeft.getIntrinsicHeight ( ) );
setCompoundDrawables ( null, getCompoundDrawables ( )[ 1 ],
drawable, getCompoundDrawables ( )[ 3 ] );
// 设置editText左,上,右,下的图片
}
@Override
/**
* 获取触摸事件的方法,判断你所点击的位置是否为图片区域
*/
public boolean onTouchEvent ( MotionEvent event ) {
if ( event.getAction ( ) == MotionEvent.ACTION_UP ) {
if ( getCompoundDrawables ( )[ 2 ] != null ) {
boolean touchable = event.getX ( ) > ( getWidth ( ) - getTotalPaddingRight ( ) ) ;
if ( touchable ) {
this.setText ( "" );
}
}
}
return super.onTouchEvent ( event );
}
@Override
/**
* 文本改变的监听器
*/
public void onTextChanged ( CharSequence s, int start, int before, int count ) {
if ( s != null ) {
setClearIconVisible ( s.length ( ) > 0 );
}
}
@Override
public void beforeTextChanged ( CharSequence s, int start, int count,
int after ) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged ( Editable s ) {
// TODO Auto-generated method stub
}
}
以上是关于java 带清空功能的的EditText的主要内容,如果未能解决你的问题,请参考以下文章