您的位置:首页 > 移动开发 > Android开发

android之自定义带清除内容的EditText

2015-02-14 13:18 411 查看
android之自定义带清除内容的EditText

     android在很多地方需要用输入框EditText,输入的内容可以完全清除,这样做的好处,是在有的地方用户体验更好,比如用户在注册登录的输入框,可以在EditText右侧加上一个按钮,点击清除用户名等;一般传统做法是在布局里面加按钮,这样感觉做法不是很好,网上研究了下,然后自己总结了一个demo分享下。有问题可以提出,欢迎讨论学习。
xml布局:
<div style="text-align: left;"><pre name="code" class="html"><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"
tools:context=".MainActivity" >

<com.example.editviewtest.MyEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入"
/>

</RelativeLayout>



自定义MyEditText:

public class MyEditText extends EditText {

private Context mContext;
private Drawable imgDel_Gray;
private Drawable imgDel_Bule;

public MyEditText(Context context) {
super(context);
mContext = context;
init();
}

public MyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}

public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}

/***
* 初始化
*/
public void init() {
// TODO Auto-generated method stub
imgDel_Gray = mContext.getResources().getDrawable(
R.drawable.delete_gray);
imgDel_Bule = mContext.getResources().getDrawable(R.drawable.delete);
setDrawble();
// 对EditText文本状态监听
this.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}

@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
setDrawble();
}
});
}

/***
* 设置图片
*/
public void setDrawble() {
if (this.length() < 1) {
/****
* 此方法意思是在EditText添加图片 参数: left - 左边图片id top - 顶部图片id right - 右边图片id
* bottom - 底部图片id
*/
this.setCompoundDrawablesWithIntrinsicBounds(null, null,
imgDel_Gray, null);
} else {
this.setCompoundDrawablesWithIntrinsicBounds(null, null,
imgDel_Bule, null);
}
}

/***
* 设置删除事件监听
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (imgDel_Bule != null && event.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 50;
if (rect.contains(eventX, eventY))
setText("");
}
return super.onTouchEvent(event);
}
}








内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: