Android EditText显示图标

实现了要给带清除按钮的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

按这个思路进一步优化,可以实现同时显示图标和Label
image

posted @ 2023-09-25 16:59  zhaogaojian  阅读(71)  评论(0编辑  收藏  举报