首页 > 其他分享 >Android EditText显示图标

Android EditText显示图标

时间:2023-09-25 17:15:17浏览次数:24  
标签:int EditText startIcon import Android null public 图标

实现了要给带清除按钮的ClearEditText,但是无法显示图标

<androidx.constraintlayout.widget.ConstraintLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_gravity="center">

       <ImageView
           android:id="@+id/iconImageViewKey"
           android:layout_width="24dp"
           android:layout_height="24dp"
           android:src="@drawable/ic_baseline_key_24"
           app:tint="@color/grid"
           android:contentDescription="Icon"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintBottom_toBottomOf="parent" />

       <com.tools.qrtestassist.component.ClearEditText
           android:id="@+id/password"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:hint="请输入密码"
           android:drawablePadding="8dp"
           android:inputType="text"
           android:maxLength="10"
           app:layout_constraintStart_toEndOf="@id/iconImageViewKey"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintBottom_toBottomOf="parent"
           app:layout_constraintBaseline_toBaselineOf="@id/iconImageViewKey" /> <!-- 使用这个属性进行垂直对齐 -->
   </androidx.constraintlayout.widget.ConstraintLayout>

这样写图标在线外不太好看,从新修改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 androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.tools.qrtestassist.R;

public class ClearEditText extends AppCompatEditText {
    private Drawable clearButton;
    private boolean hasFocus = false;

    public ClearEditText(Context context) {
        super(context);
        init();
    }

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

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

    private void init() {
        clearButton = new ClearIconDrawable(getContext());

        int iconColor = ContextCompat.getColor(getContext(), R.color.grid); // 将 icon_color 替换为实际的颜色资源
        // 获取XML中定义的drawableStart图标
        Drawable[] drawables = getCompoundDrawablesRelative();
        Drawable startIcon = drawables[0];

        if (startIcon != null) {
            startIcon = DrawableCompat.wrap(startIcon);
            DrawableCompat.setTint(startIcon, iconColor);
            startIcon.setBounds(0, 0, startIcon.getIntrinsicWidth(), startIcon.getIntrinsicHeight());
            // 设置drawableStart图标的位置和大小
        }

        // 设置左边的drawableStart图标和右边的清除图标
        setCompoundDrawablesRelativeWithIntrinsicBounds(startIcon, null, clearButton, null);

        setClearIconVisible(false);

        this.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                ClearEditText.this.hasFocus = hasFocus;
                setClearIconVisible(hasFocus);
                // 如果为空,即使有焦点,也不显示
                if (ClearEditText.this.getText().toString().equals(""))
                    setClearIconVisible(false);
            }
        });

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

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

            @Override
            public void afterTextChanged(Editable s) {
                setClearIconVisible(hasFocus && s.length() > 0);
            }
        });
    }

    private void setClearIconVisible(boolean visible) {

        Drawable[] drawables = getCompoundDrawablesRelative();
        Drawable startIcon = drawables[0];
        if(startIcon!=null)
        {
            startIcon = DrawableCompat.wrap(startIcon);
            startIcon.setBounds(0, 0, startIcon.getIntrinsicWidth(), startIcon.getIntrinsicHeight());
        }
        setCompoundDrawablesRelativeWithIntrinsicBounds(startIcon, null, visible ? clearButton : null, null);
        //Drawable startIcon = getCompoundDrawablesRelative()[0]; // 获取drawableStart图标
        //setCompoundDrawables(startIcon, null, visible ? clearButton : null, null);
        //setCompoundDrawables(null, null, visible ? clearButton : null, null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (clearButton != null) {
                int touchX = (int) event.getX();
                if (touchX > (getWidth() - getPaddingEnd() - clearButton.getIntrinsicWidth())) {
                    setText("");
                    return true;
                }
            }
        }
        return super.onTouchEvent(event);
    }
}

最终效果
image
同时支持x按钮
image

标签:int,EditText,startIcon,import,Android,null,public,图标
From: https://www.cnblogs.com/zhaogaojian/p/17728335.html

相关文章

  • Android 多选下拉框的简单实现
    1、布局文件(activity_dropdown.xml)<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"to......
  • android驱动模块实现文件重定位
    编写驱动模块进行sys_call_tablehook替换sys_open和sys_openat系统调用为自定义函数,需要注意sys_call_table是只读的,修改前需要前修改其内存属性为可写。直接修改内核源码,并编写驱动模块实现filterfunction进行过滤。sys_call_tablehook只能对系统调用函数进行hook。而第......
  • R3300L, Q7 ATV Android9固件
    R3300L,Q7ATVAndroid9固件固件来源https://www.znds.com/tv-1239603-1-1.html之前在恩山上发布过1080p安卓6固件https://www.right.com.cn/forum/thread-1761250-1-1.html,这个固件的不足之处就是没有GoogleServiceFramework,只能通过SmartYoutube之类的第三方APP......
  • Android 9关机流程
    一、整体关机流程framework->init->kernel二、关机流程(代码)本文基于Android9,梳理下正常power键触发的关机流程。涉及的相关代码路径如下://frameworkframeworks\base\core\res\res\values\config.xmlframeworks\base\services\core\java\com\android\server\policy\LegacyG......
  • 过来Android码农提醒,不要有面试就去,可能会白跑一趟
    前言亲身经历!!面试失败总结(它失败,我也不想要的那种)正值毕业季,毕业生开始走向求职之路,大量求职者随之而来。再加上现在正值金九银十招聘的火热阶段。找工作的都知道,工作成功的最后一步是面试,所以很多求职者都选择有面试就去,这是不可取的。就拿本人最近的面试来说,通勤一个小时,明明之前......
  • Android程序员35岁的职业出路:寻找新的舞台
    前言转眼间已经到了奔四的年纪,岁月匆匆,时光荏苒,转眼间已经在Android行业干了8年,当前项目组也陆陆续续进入了不少00后,80后已经不见踪影,90后正在逐渐淡出,而我,也要开始迎接程序员35岁这个坎,心里还是想要继续做技术这条路,但是也给自己思索了一些转行之路,在此跟大家交流交流。为什么35岁......
  • Android DataBinding——导入以及生成的绑定类
    导入DataBinding库提供了导入、变量和include等功能。导入可以方便在引用布局文件中引用类;变量允许您描述可在绑定表达式中使用的属性;Includes允许您在整个应用程序中重用复杂的布局。ImportsImports允许您轻松地在布局文件中的引用类,就像在代码中一样。data元素内部可以使用零个或......
  • Android Failed to resolve: com.github.PhilJay:MPAndroidChart:v3.1.0
    2022.3.1版本修改settings.gradledependencyResolutionManagement{repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)repositories{maven{url"https://jitpack.io"}//Addthisrepositoryjcenter()//orotherrep......
  • 熬过月余终见offer,一份Android面经
    前言最近我一直在牛客刷帖子看到好多对于现在IT环境的负面消息,自己也是找了一个多月Offer一个都没有,又看到这些感觉面试的勇气又少了…这种状态我根本就不知道任何转变,真的是投简历都不想投!就在这样的状态下,朋友说他那边内推有消息了,说待会HR会和我联系。怎么说了,并没有太多惊喜,因......
  • 干货:《Android 性能优化实战篇》带你杀穿金九银十
    近年来,由于疫情和互联网行业寒冬的影响,Android开发领域的竞争变得更加激烈。各大公司的业务线收缩和裁员成为了常规操作,导致职场环境日益严峻。作为一个螺丝钉,我们想要卷出重围,性能优化必须了解一下!本文将梳理Android性能优化的知识模块,帮助初学者了解应该从哪些方面入手学习性能优......