Android 自定义EditText

文章目录

  • Android 自定义EditText
    • 概述
    • 源码
      • 可清空内容的EditText
      • 可显示密码的EditText
    • 使用
    • 源码下载

Android 自定义EditText

概述

定义一款可清空内容的 ClearEditText 和可显示密码的 PasswordEditText,支持修改提示图标和大小、背景图片等。

在这里插入图片描述

源码

基类:

open class BaseEditText @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = android.R.attr.editTextStyle
) : androidx.appcompat.widget.AppCompatEditText(context, attrs, defStyleAttr) {companion object {@JvmStaticprotected val DEFAULT_DRAWABLE = ColorDrawable(0xFFFFFFFF.toInt())}init {gravity = Gravity.CENTER_VERTICALbackground = DEFAULT_DRAWABLE}override fun setLayoutParams(params: ViewGroup.LayoutParams) {if (params.width == ViewGroup.LayoutParams.WRAP_CONTENT) {params.width = ViewGroup.LayoutParams.MATCH_PARENT}super.setLayoutParams(params)}
}

可清空内容的EditText

定义属性:

<declare-styleable name="ClearEditText"><attr name="cet_deleteIcon" format="reference" /><attr name="cet_deleteIconSize" format="dimension" /><attr name="cet_tipDefaultIcon" format="reference" /><attr name="cet_tipSelectedIcon" format="reference" /><attr name="cet_tipIconSize" format="dimension" /><attr name="cet_defaultBg" format="color|reference" /><attr name="cet_selectedBg" format="color|reference" />
</declare-styleable>

定义ClearEditText:

class ClearEditText @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null
) : BaseEditText(context, attrs) {private val deleteIconDrawable: Drawable?private val tipIconDefaultDrawable: Drawable?private val tipIconSelectedDrawable: Drawable?private val bgDefaultDrawable: Drawable?private val bgSelectedDrawable: Drawable?init {val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText)val deleteIconSize =a.getDimensionPixelSize(R.styleable.ClearEditText_cet_deleteIconSize, 0)deleteIconDrawable = a.getDrawable(R.styleable.ClearEditText_cet_deleteIcon)deleteIconDrawable?.let { it ->if (deleteIconSize > 0) {it.setBounds(0, 0, deleteIconSize, deleteIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}val tipIconSize = a.getDimensionPixelSize(R.styleable.ClearEditText_cet_tipIconSize, 0)tipIconDefaultDrawable = a.getDrawable(R.styleable.ClearEditText_cet_tipDefaultIcon)tipIconDefaultDrawable?.let { it ->if (tipIconSize > 0) {it.setBounds(0, 0, tipIconSize, tipIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}tipIconSelectedDrawable = a.getDrawable(R.styleable.ClearEditText_cet_tipSelectedIcon)tipIconSelectedDrawable?.let { it ->if (tipIconSize > 0) {it.setBounds(0, 0, tipIconSize, tipIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}bgDefaultDrawable = a.getDrawable(R.styleable.ClearEditText_cet_defaultBg)bgSelectedDrawable = a.getDrawable(R.styleable.ClearEditText_cet_selectedBg)a.recycle()setup()}private fun setup() {setIconVisible(false, false)bgDefaultDrawable?.let {background = it}}override fun onTextChanged(text: CharSequence,start: Int,lengthBefore: Int,lengthAfter: Int) {super.onTextChanged(text, start, lengthBefore, lengthAfter)setIconVisible(hasFocus() && text.length > 0, hasFocus())}override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {super.onFocusChanged(focused, direction, previouslyFocusedRect)setIconVisible(focused && length() > 0, focused)}private fun setIconVisible(deleteIconVisible: Boolean, focused: Boolean) {setCompoundDrawablesRelative(if (focused) tipIconSelectedDrawable else tipIconDefaultDrawable,null,if (deleteIconVisible) deleteIconDrawable else null,null)if (bgDefaultDrawable != null && bgSelectedDrawable != null) {background = if (focused) bgSelectedDrawable else bgDefaultDrawable}}override fun onTouchEvent(event: MotionEvent): Boolean {if (event.action == MotionEvent.ACTION_UP) {val drawable = deleteIconDrawableif (drawable != null) {if (event.x <= width - paddingRight && event.x >= width - paddingRight - drawable.bounds.width()) {text = null}}}return super.onTouchEvent(event)}
}

可显示密码的EditText

定义属性:

<declare-styleable name="PasswordEditText"><attr name="pet_eyeIconSize" format="dimension" /><attr name="pet_tipDefaultIcon" format="reference" /><attr name="pet_tipSelectedIcon" format="reference" /><attr name="pet_tipIconSize" format="dimension" /><attr name="pet_defaultBg" format="color|reference" /><attr name="pet_selectedBg" format="color|reference" />
</declare-styleable>

定义PasswordEditText:

class PasswordEditText @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null
) : BaseEditText(context, attrs) {private val eyeOpenDrawable: Drawable?private val eyeCloseDrawable: Drawable?private var currentEyeDrawable: Drawable? = nullprivate var tipIconDefaultDrawable: Drawable?private var tipIconSelectedDrawable: Drawable?private var bgDefaultDrawable: Drawable?private var bgSelectedDrawable: Drawable?init {val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.PasswordEditText)val eyeIconSize = a.getDimensionPixelSize(R.styleable.PasswordEditText_pet_eyeIconSize, 0)eyeOpenDrawable = ContextCompat.getDrawable(context, R.drawable.eye_open)eyeOpenDrawable?.let {if (eyeIconSize > 0) {it.setBounds(0, 0, eyeIconSize, eyeIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}eyeCloseDrawable = ContextCompat.getDrawable(context, R.drawable.eye_close)eyeCloseDrawable?.let {if (eyeIconSize > 0) {it.setBounds(0, 0, eyeIconSize, eyeIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}val tipIconSize = a.getDimensionPixelSize(R.styleable.PasswordEditText_pet_tipIconSize, 0)tipIconDefaultDrawable = a.getDrawable(R.styleable.PasswordEditText_pet_tipDefaultIcon)tipIconDefaultDrawable?.let { it ->if (tipIconSize > 0) {it.setBounds(0, 0, tipIconSize, tipIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}tipIconSelectedDrawable = a.getDrawable(R.styleable.PasswordEditText_pet_tipSelectedIcon)tipIconSelectedDrawable?.let { it ->if (tipIconSize > 0) {it.setBounds(0, 0, tipIconSize, tipIconSize)} else {it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)}}bgDefaultDrawable = a.getDrawable(R.styleable.PasswordEditText_pet_defaultBg)bgSelectedDrawable = a.getDrawable(R.styleable.PasswordEditText_pet_selectedBg)a.recycle()setup()}private fun setup() {setIconVisible(false, false)currentEyeDrawable = eyeCloseDrawablebgDefaultDrawable?.let {background = it}inputType = InputType.TYPE_TEXT_VARIATION_PASSWORDtransformationMethod = PasswordTransformationMethod.getInstance()}override fun onTextChanged(text: CharSequence,start: Int,lengthBefore: Int,lengthAfter: Int) {super.onTextChanged(text, start, lengthBefore, lengthAfter)setIconVisible(hasFocus() && text.length > 0, hasFocus())}override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {super.onFocusChanged(focused, direction, previouslyFocusedRect)setIconVisible(focused && length() > 0, focused)}private fun setIconVisible(pwdIconVisible: Boolean, focused: Boolean) {setCompoundDrawablesRelative(if (focused) tipIconSelectedDrawable else tipIconDefaultDrawable,null,if (pwdIconVisible) currentEyeDrawable else null,null)if (bgDefaultDrawable != null && bgSelectedDrawable != null) {background = if (focused) bgSelectedDrawable else bgDefaultDrawable}}override fun onTouchEvent(event: MotionEvent): Boolean {if (event.action == MotionEvent.ACTION_UP) {val drawable = currentEyeDrawableif (drawable != null) {if (event.x <= width - paddingRight && event.x >= width - paddingRight - drawable.bounds.width()) {if (drawable == eyeOpenDrawable) {// 密码不可见currentEyeDrawable = eyeCloseDrawabletransformationMethod = PasswordTransformationMethod.getInstance()refreshDrawables()} else if (drawable == eyeCloseDrawable) {// 密码可见currentEyeDrawable = eyeOpenDrawabletransformationMethod = HideReturnsTransformationMethod.getInstance()refreshDrawables()}}}}return super.onTouchEvent(event)}private fun refreshDrawables() {val drawables = compoundDrawablesRelativesetCompoundDrawablesRelative(drawables[0], drawables[1], currentEyeDrawable, drawables[3])}
}

使用

<com.example.widgets.custom_edittext.ClearEditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginHorizontal="30dp"android:layout_marginTop="60dp"android:hint="请输入用户名"android:padding="10dp"android:singleLine="true"android:textSize="20sp"app:cet_defaultBg="@drawable/shape_border_gray"app:cet_deleteIcon="@drawable/ic_delete_x"app:cet_deleteIconSize="30dp"app:cet_selectedBg="@drawable/shape_border_blue"app:cet_tipDefaultIcon="@drawable/ic_user_gray"app:cet_tipIconSize="30dp"app:cet_tipSelectedIcon="@drawable/ic_user_blue" /><com.example.widgets.custom_edittext.ClearEditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginHorizontal="30dp"android:layout_marginTop="30dp"android:hint="请输入手机号"android:inputType="phone"android:padding="10dp"android:textSize="20sp"app:cet_defaultBg="@drawable/shape_border_gray"app:cet_deleteIcon="@drawable/ic_delete_x"app:cet_deleteIconSize="30dp"app:cet_selectedBg="@drawable/shape_border_blue"app:cet_tipDefaultIcon="@drawable/ic_user_gray"app:cet_tipIconSize="30dp"app:cet_tipSelectedIcon="@drawable/ic_user_blue" /><com.example.widgets.custom_edittext.PasswordEditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginHorizontal="30dp"android:layout_marginTop="30dp"android:hint="请输入密码"android:padding="10dp"android:textSize="20sp"app:pet_defaultBg="@drawable/shape_border_gray"app:pet_selectedBg="@drawable/shape_border_blue"app:pet_tipDefaultIcon="@drawable/ic_lock_gray"app:pet_tipIconSize="30dp"app:pet_tipSelectedIcon="@drawable/ic_lock_blue" />

源码下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/782005.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WebViz可视化

WebViz可视化 Webviz是一个基于Web的可视化工具&#xff0c;意味着您可以通过浏览器/APP访问它&#xff0c;而不需要安装额外的软件。这对于远程访问和团队协作非常方便。 Foxglove是一个开源的工具包&#xff0c;包括线上和线下版。旨在简化机器人系统的开发和调试。它提供了…

Gitea 的详细介绍

什么是 Gitea&#xff1f; Gitea 是一个开源、轻量级的自托管 Git 服务&#xff0c;它允许用户搭建类似于 GitHub 或 GitLab 的代码托管平台。由于采用 Go 语言开发&#xff0c;Gitea 具有高效的性能和跨平台特性&#xff0c;适合个人开发者或小团队使用。 Gitea 的特点 轻量…

蓝桥杯第十三届电子类单片机组程序设计

目录 前言 单片机资源数据包_2023 一、第十三届比赛省赛 1.比赛题目 2.赛题解读 二、部分功能实现 1.继电器的开启与关闭 2.长按切换显示状态功能的实现 3.对于温度传感器小数部分的处理 4.其他处理 1&#xff09;关于数码管显示小数的处理 2&#xff09;关于5s后继…

SpringBoot + LiteFlow(二):LiteFlow特性和环境支持

项目特性 组件定义统一: 所有的逻辑都是组件,为所有的逻辑提供统一化的组件实现方式,小身材,大能量。规则轻量: 基于规则文件来编排流程,学习规则入门只需要5分钟,一看即懂。规则多样化: 规则支持xml、json、yml三种规则文件写法方式,喜欢哪种用哪个。任意编排: 再复…

简易TCP服务器通信、IO多路复用(select、poll、epoll)以及reactor模式。

网络编程学习 简单TCP服务器通信三次握手和四次挥手状态转换总结client和server通信写法server端client端 怎么应对多用户连接&#xff1f;缺点 IO多路复用select优缺点 pollpoll写法和改进点 epoll&#xff08;使用最多&#xff0c;重中之重&#xff09;epoll写法和改进点LT模…

结构体类型,结构体变量的创建和初始化 以及结构中存在的内存对齐

一般结构体类型的声明 struct 结构体类型名 { member-list; //成员表列 }variable-list; //变量表列 例如描述⼀个学⽣&#xff1a; struct Stu { char name[20]; //名字 int age; //年龄 char sex[5]; //性别 }&#xff1b; //结构体变量的初始化 int main() { S…

牛客NC30 缺失的第一个正整数【simple map Java,Go,PHP】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5 核心 Map参考答案Java import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定&#xff0c;请勿修改&#xff0c;直接返回方法规定的值即可…

Modelsim手动仿真实例

目录 1. 软件链接 2. 为什么要使用Modelsim 3. Modelsim仿真工程由几部分组成&#xff1f; 4. 上手实例 4.1. 新建文件夹 4.2. 指定目录 4.3. 新建工程 4.4. 新建设计文件&#xff08;Design Files&#xff09; 4.5. 新建测试平台文件&#xff08;Testbench Files&…

企业数据被新型.rmallox勒索病毒加密,应该如何还原?

.rmallox勒索病毒为什么难以解密&#xff1f; .rmallox勒索病毒难以解密的主要原因在于其采用了高强度的加密算法&#xff0c;并且这些算法被有效地实施在了病毒程序中。具体来说&#xff0c;.rmallox勒索病毒使用了RSA和AES这两种非常成熟的加密算法。RSA是一种非对称加密算法…

08、Lua 函数

Lua 函数 Lua 函数Lua函数主要有两种用途函数定义解析&#xff1a;optional_function_scopefunction_nameargument1, argument2, argument3..., argumentnfunction_bodyresult_params_comma_separated 范例 : 定义一个函数 max()Lua 中函数可以作为参数传递给函数多返回值Lua函…

Laravel 数据库:判断数据表是否存在

检测某个表是否存在&#xff1a; if (Schema::hasTable(table_name)) { // } 在某个表不存在的情况下再执行创建操作&#xff1a; if ( ! Schema::hasTable(table_name)) { // 创建数据库表的代码 } 如果你想安全的 drop 掉一个数据表&#xff0c;使用以下&#xf…

蓝桥杯刷题记录之蓝桥王国

只是记录 这题用迪杰斯特拉来就行&#xff0c;我写的是堆优化版本 import java.util.*;public class Main{static Scanner s new Scanner(System.in);static int n,m,startPoint1;static List<Edge>[] table;//邻接表,因为是稀疏图static long[] dist;static boolean[] …

Day25 代码随想录(1刷) 回溯

39. 组合总和 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target &#xff0c;找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 &#xff0c;并以列表形式返回。你可以按 任意顺序 返回这些组合。 candidates 中的 同一个 数字可以 无限制重复…

3D汽车模型线上三维互动展示提供视觉盛宴

VR全景虚拟看车软件正在引领汽车展览行业迈向一个全新的时代&#xff0c;它不仅颠覆了传统展览的局限&#xff0c;还为参展者提供了前所未有的高效、便捷和互动体验。借助于尖端的vr虚拟现实技术、逼真的web3d开发、先进的云计算能力以及强大的大数据处理&#xff0c;这一在线展…

瑞吉外卖实战学习--6、通过try和catch进行异常处理

try和catch进行异常处理 效果图前言1、公共拦截器进行异常处理1.1、创建公共报错处理的方法1.2、@ControllerAdvice中设置要拦截的类1.3、@ExceptionHandler中写处理的异常类2、完善错误拦截器2.1、效果效果图 前言 当用户名重复数据库会报错,此时就需要捕获异常操作 1、公共…

Spring: 在SpringBoot项目中解决前端跨域问题

这里写目录标题 一、什么是跨域问题二、浏览器的同源策略三、SpringBoot项目中解决跨域问题的5种方式&#xff1a;使用CORS1、自定 web filter 实现跨域(全局跨域)2、重写 WebMvcConfigurer(全局跨域)3、 CorsFilter(全局跨域)4、使用CrossOrigin注解 (局部跨域) 一、什么是跨域…

社交网络的未来:Facebook如何塑造数字社交的下一章

引言 社交网络已成为我们生活中不可或缺的一部分&#xff0c;而Facebook作为其领军者&#xff0c;一直在塑造着数字社交的未来。本文将深入探讨Facebook在未来如何塑造数字社交的下一章&#xff0c;并对社交网络的发展趋势进行展望和分析。 1. 引领虚拟社交的潮流 Facebook将…

Lombok之@SneakyThrows

1前言&#xff1a; 这里记录一个SneakyThrows的用法&#xff0c;关于他的用法&#xff0c;在官网上可以知道的很清楚 官网介绍&#xff1a;http://projectlombok.org/features/SneakyThrows.html 2代码示例 个人理解&#xff1a;在代码中&#xff0c;使用 try&#xff0c;cat…

C++vector和C语言数组的区别

vector 是 C 标准模板库&#xff08;STL&#xff09;中的一个类模板&#xff0c;它提供了一个动态数组的功能&#xff0c;能够根据需要自动增长或缩小。而 C 语言数组则是 C 语言提供的一种固定大小的序列容器。下面是 vector 和 C 语言数组之间的一些主要区别&#xff1a; 动…

VRP and related algorithms for logistics distribution综述的笔记

选了些自己感兴趣的。 车辆路径问题(VRP)是当今物流公司面临的最关键挑战之一。自1959年丹齐格和兰姆泽(1959年)介绍了卡车调度问题以来,研究人员一直在研究车辆路由和交付调度。它被认为是车辆路径问题(VRP)的范例,并且涉及从中央仓库到地理分散的客户的货物配送。 自…