如何仅在EditText填写完成或被触摸时显示drawableRight图标
实现方案
前置步骤:初始化隐藏右侧图标
你布局中已经给EditText配置了右侧图标资源,首先在Activity/Fragment初始化阶段先把图标隐藏:
// Kotlin代码 val mobileEt = findViewById<EditText>(R.id.mobiledes) // 四个参数分别对应左、上、右、下位置的drawable,设为0即隐藏对应位置图标 mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
// Java代码 EditText mobileEt = findViewById(R.id.mobiledes); mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
方案1:输入满10位数字时显示右侧图标
给EditText添加文本变化监听器,判断输入长度控制图标显隐:
// Kotlin代码 mobileEt.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { s?.let { if (it.length == 10) { // 输入长度达标,显示右侧图标 mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verifybutton, 0) } else { // 输入长度不足,隐藏图标 mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0) } } } })
// Java代码 mobileEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() == 10) { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verifybutton, 0); } else { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } } });
方案2:EditText被触摸时就显示右侧图标
给EditText添加触摸监听器,触摸时显示图标,可搭配焦点监听实现失去焦点后自动隐藏:
// Kotlin代码 // 触摸时显示图标 mobileEt.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_DOWN) { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verifybutton, 0) } // 返回false不消费触摸事件,不影响EditText原生交互逻辑 false } // 可选配置:失去焦点后隐藏图标 mobileEt.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0) } }
// Java代码 // 触摸时显示图标 mobileEt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verifybutton, 0); } return false; } }); // 可选配置:失去焦点后隐藏图标 mobileEt.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { mobileEt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } } });
可选优化:自定义图标显示大小
如果默认显示的图标尺寸不符合预期,可以手动调整drawable大小后再设置:
val drawable = ContextCompat.getDrawable(this, R.drawable.ic_verifybutton) // 按需求调整图标大小,示例为24dp,需自行实现dp转px的工具方法 drawable?.setBounds(0, 0, dp2px(24), dp2px(24)) mobileEt.setCompoundDrawables(null, null, drawable, null)
内容的提问来源于stack exchange,提问作者Kumar Harsh
相关产品推荐
相关产品推荐

