给EditText左右两边设置图片与监听(drawableLeft/drawableRight)/弹出键盘

本文介绍了如何在Android的EditText中设置左右两侧的图片,并实现点击图片的监听事件。通过自定义View并重写onTouchEvent方法,可以监听到用户对图片的点击操作。同时,展示了如何在EditText获得焦点时显示右侧图片,失去焦点时隐藏,以及自动弹出键盘的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置图片:

Drawable phoneDrawableLeft = getResources().getDrawable(R.mipmap.phone_login, null);
phoneDrawableLeft.setBounds(0, 0, drawableDimension, drawableDimension);

Drawable phoneDrawableRight = getResources().getDrawable(R.mipmap.empty, null);
phoneDrawableRight.setBounds(0, 0, drawableDimension, drawableDimension);

mEtPhone.setCompoundDrawables(phoneDrawableLeft, null, phoneDrawableRight, null);
mEtPhone.setCompoundDrawablePadding(Utils.dp2px(this, 5));



设置监听:自定义View集成EditText,然后重写onTouchEvent方法,注意getX()获取的是View在屏幕X轴的坐标,不是相对坐标:

public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            Drawable right = getCompoundDrawables()[2];  //获取右边图片
            Drawable left = getCompoundDrawables()[0];  //获取左边图片

            if ((right != null) && (event.getRawX() >= (getX() + (getWidth() - right.getBounds().width()))) && mDrawableRightListener != null) {
                mDrawableRightListener.onDrawableClick();
                return true;
            }

            if ((left != null) && (event.getRawX() <= (getX() + left.getBounds().width())) && mDrawableLeftListener != null) {
                mDrawableLeftListener.onDrawableClick();
                return true;
            }
            break;
    }
    return super.onTouchEvent(event);
}

public void setDrawableRightListener(DrawableListener l) {
    mDrawableRightListener = l;
}

public void setDrawableLeftListener(DrawableListener l) {
    mDrawableLeftListener = l;
}

public interface DrawableListener {
    public void onDrawableClick();
}



设置焦点变化监听:

//设置焦点变化监听
mEtPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            mEtPhone.setCompoundDrawables(phoneDrawableLeft, null, phoneDrawableRight, null);
        } else {
            mEtPhone.setCompoundDrawables(phoneDrawableLeft, null, null, null);
        }
    }
});



自动弹出键盘:

//弹出键盘
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值