Android Edittext 清空按钮功能 自定义

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

本文参考网络内容,感谢网友分享!


1. 自定义ClearEditText


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.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;

import com.cn.fujielectric.fhs.opsys.android.R;

public class ClearEditText extends EditText implements OnFocusChangeListener,
		TextWatcher {
	/**
	 * 删除按钮的引用
	 */
	private Drawable mClearDrawable;
	/**
	 * 控件是否有焦点
	 */
	private boolean hasFoucs;

	public ClearEditText(Context context) {
		this(context, null);
	}

	public ClearEditText(Context context, AttributeSet attrs) {
		// 这里构造方法也很重要,不加这个很多属性不能再XML里面定义
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
		mClearDrawable = getCompoundDrawables()[2];
		if (mClearDrawable == null) {
			// throw new
			// NullPointerException("You can add drawableRight attribute in XML");
			mClearDrawable = getResources().getDrawable(R.drawable.delete);
		}

		mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
				mClearDrawable.getIntrinsicHeight());
		// 默认设置隐藏图标
		setClearIconVisible(false);
		// 设置焦点改变的监听
		setOnFocusChangeListener(this);
		// 设置输入框里面内容发生改变的监听
		addTextChangedListener(this);
	}

	/**
	 * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件 当我们按下的位置 在 EditText的宽度 -
	 * 图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if (getCompoundDrawables()[2] != null) {

				boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
						&& (event.getX() < ((getWidth() - getPaddingRight())));

				if (touchable) {
					this.setText("");
				}
			}
		}

		return super.onTouchEvent(event);
	}

	/**
	 * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
	 */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		this.hasFoucs = hasFocus;
		if (hasFocus) {
			setClearIconVisible(getText().length() > 0);
		} else {
			setClearIconVisible(false);
		}
	}

	/**
	 * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
	 * 
	 * @param visible
	 */
	protected void setClearIconVisible(boolean visible) {
		Drawable right = visible ? mClearDrawable : null;
		setCompoundDrawables(getCompoundDrawables()[0],
				getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
	}

	/**
	 * 当输入框里面内容发生变化的时候回调的方法
	 */
	@Override
	public void onTextChanged(CharSequence s, int start, int count, int after) {
		if (hasFoucs) {
			setClearIconVisible(s.length() > 0);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	/**
	 * 设置晃动动画
	 */
	public void setShakeAnimation() {
		// this.setAnimation(shakeAnimation(5));
		this.startAnimation(shakeAnimation(5));
	}

	/**
	 * 晃动动画
	 * 
	 * @param counts
	 *            1秒钟晃动多少下
	 * @return
	 */
	public static Animation shakeAnimation(int counts) {
		Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
		translateAnimation.setInterpolator(new CycleInterpolator(counts));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

}


2. 布局(仅贴输入框部分)


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1.5"
        android:gravity="bottom" >

        <TextView
            android:id="@+id/txv_username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_weight="1.5"
            android:text="@string/user_name"
            android:textSize="@dimen/BigLabelFontSize" />

        <com.csdnadcode.android.weight.ClearEditText
            android:id="@+id/edt_username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight="4"
            android:background="@drawable/edit_bg_login"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:singleLine="true" >
        </com.csdnadcode.android.weight.ClearEditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <View
            android:layout_width="10dp"
            android:layout_height="0.5dp"
            android:background="#FFFFFF" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.5dp"
            android:background="#D4D4D4" />

        <View
            android:layout_width="10dp"
            android:layout_height="0.5dp"
            android:background="#FFFFFF" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1.5"
        android:gravity="bottom" >

        <TextView
            android:id="@+id/txv_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_weight="1.5"
            android:text="@string/pass_word"
            android:textSize="@dimen/BigLabelFontSize" />

        <com.csdnadcode.android.weight.ClearEditText
            android:id="@+id/edt_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight="4"
            android:background="@drawable/edit_bg_login"
            android:inputType="textPassword"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:singleLine="true" >
        </com.csdnadcode.android.weight.ClearEditText>
    </LinearLayout>


3.代码实现


	// 用户名输入框
	private ClearEditText edtUserCode = null;
	// 密码输入框
	private ClearEditText edtPassWord = null;

<span style="white-space:pre">	</span>edtUserCode = (ClearEditText) this.findViewById(R.id.edt_username);
	edtPassWord = (ClearEditText) this.findViewById(R.id.edt_password);
<span style="white-space:pre">	edtUserCode.setSelection(edtUserCode.getText().length());
<span style="white-space:pre">	</span>edtPassWord.setSelection(edtPassWord.getText().length());</span>
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>//设置晃动效果
<span style="white-space:pre">	</span>edtUserCode.setShakeAnimation();
<span style="white-space:pre">	</span>edtPassWord.setShakeAnimation();



Android 自定义EditText输入框清空按钮,flutter二维码扫描第三方 super(paramContext); initEditText(); } public MyEditText(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); initEditText(); } public MyEditText(Context paramContext, AttributeSet paramAttributeSet, int paramInt) 阅读详情

相关推荐

Android自定义带清除功能EditText实战教程

Android开发中,XML布局文件为视图组件的属性提供了丰富的定义方式。对于EditText组件而言,通过其XML属性可以实现外观和行为的初步定制。属性如和等,可以定义输入框的基本功能、提示文本、是否单行显示以及布局尺寸。举一个例子,以下是一段定义EditText的XML代码:<EditText在这段代码中,inputType属性确保了输入框能够提供适合文本类型(如名字)的键盘输入法。ems。

weixin_42581003的博客 952

Android输入框控件ClearEditText实现清除功能

主要为大家详细介绍了Android输入框控件ClearEditText实现清除功能,感兴趣的小伙伴们可以参考一下

cleanedittext

带clean图标的EditText.

AndroidClearEditText实现点击EditText输入框右边清除图标来清除输入内容的两种方式

两种EditText输入框点击右边清除图标来实现清除功能的方式。 效果图下图: 布局代码如下, <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_

daitu_liang的博客 8378

android重置按钮,android – 如何在动作完成后重置EditText

我想在按下按钮后将EditText重置为空的“空格”或“提示”,该按钮将完成来自EditText字段输入的活动.我的Android冒险因此召唤.干杯.谢谢 !!//************-------------------SEND SMS----------------*********//btnSendSMS = (Button)findViewById(R.id.sms);btnSendS...

weixin_35804997的博客 1060

EditText一键清空内容

俩种方式实现EditText一键清空内容!一种为原生,一种为 网上摘抄的较老自定义控件!We must day day up!!!

带有一键清空功能EditText

介绍  很常见的一个功能,大部分app在登录界面都会实现这个功能了。因为在掘金上看了一篇类似的文章,所以决定自己实践一下。   下图为实现效果:常见实现方法 组合控件,EditText + Button  实现简单,可以单独使用。 自定义View,继承EditText,通过EditText自带的Drawable来实现。  布局复杂度低 继承EditText来实现一键清功能需要考虑的问题根据业务

Siobhan的专栏 4931

Android 自定义EditText输入框清空按钮

addTextChangedListener(new TextWatcher() { // 对文本内容改变进行监听。// 距离屏幕的距离。设置光标的颜色 设置@null 表示光标的颜色和输入框的字体颜色相同。android:cursorVisible=“false”//隐藏。android:cursorVisible=“true”//显示。// 初始化edittext 控件。// 控制图片的显示。

2501_90499511的博客 855

java删除按钮_Android自定义带有清空删除按钮EditText控件

Android EditText控件中,我们如何自定义带有清空删除按钮EditText控件呢?非常的简单,我们只需要创建一个CleanableEditText类,继承于EditText即可,代码如下:packagecom.tpyyes.shouxie;importandroid.content.Context;importandroid.graphics.drawable.Drawabl...

weixin_34281191的博客 487

android editText一键清空功能! 详细步骤

有LinearLayout+EditText+ImageView 的组合 也有自己封装实现在xml中使用

weixin_57038660的博客 3077

Android输入框带删除按钮自定义View

package com.aiitec.widgets; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawa

灵木111的博客 1328

android edittext 右边按钮,Android 自定义EditText, 增加设置右边取消按钮的属性

想要使用android自带的editText的drawable实现右边取消按钮的设置,但是设置之后,drawableRight并没有点击事件,因此本文在继承editText的基础上增加 setClearDrawMode属性,可以直接在layout的xml文件中配置实现上述功能,第一步在values下新建 attrs.xml文件 第二步新建UpEditText 继承EditText类public c...

weixin_28713083的博客 567

带删除按钮EditText

package com.example.administrator.newspolice.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; im...

爱上网的大花猫 614

android自定义清空内容的TextView

android自定义清空内容的TextView 代码: /** * 带删除按钮EditText * @author Administrator * */ public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { /** * 删除按钮的引用 */

小白james 1万+

Android自定义EditText带清除功能

首先声明我也是参考了别人的思路,只是稍微做了下修改,增加显示密码与隐藏密码,没有输入字符串时让EditText进行抖动,废话少说这里附上效果图 效果很赞有木有 那么怎么实现这种效果呢?那就跟着我一起来吧 首先我们先分析一下清除功能怎么实现的,我们怎么知道用户点击的是清除按钮还是别的地方呢?,而EditText其实是集成Textview的, 而Textview有方法getTotal...

luhan_cc的博客 700

35.Android之带删除按钮EditText学习

今天实现Android自定义带删除功能EditText,效果如下: 当输入内容时,EditText变为带有一个删除功能按钮的编辑框,如图: 实现代码很简单,直接上代码, 布局文件xml: 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://s...

weixin_30902251的博客 194

带有清空功能EditTtxt

带有清空按钮EditText开源库效果图:基本介绍如下:使用方式:一.添加库依赖1. 项目的build.gradle下添加 allprojects { repositories { ... maven { url 'https://jitpack.io' } } }2. app的build.gradle下

Brioal Is Hardworking 447

EditText有内容时显示清空按钮,无内容时不显示

/** * Created by xiaoyee on 4/27/15 * 用户检测edittext输入状态,如果有内容,那么显示清空按钮,如果没有内容,则清空 * <p> * 用法: * <br/>edittext.addTextChangedListener(new InputWatcher(btnClear, etContent)); * <br/>{@li

沐怡旸的专栏 2205
上一篇: Android DatePicker 限制日期选择范围
下一篇: Android Edittext 清空按钮功能的实现
KeenSpace
博客等级 码龄12年 4粉丝 29原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值