Android 自定义View--实现带有按钮点击效果的自动补全输入框(搜索框)

  在开发中,输入框和搜索框是我们非常频繁的用到的控件,针对输入Android提供了EditText 和AutoCompleteTextView。

  在Android提供的控件中我们可以为AutoCompleteTextView设置一个Adapter从而提供输入补全的功能,但是很遗憾,虽然这两个控件提供了给四周增加图片的功能,却没有提供设置点击事件。

所以我想通过现有的AutoCompleteTextView控件尽量简单易用的实现一个带有右侧点击按钮的输入框(实现清除输入内容,或者进行搜索等操作,自定义使用)如图



在此我继承AutoCompleteTextView,增加了部分代码,实现对输入框右侧图片设置点击事件,使用非常灵活和简单。代码也非常轻量。

直接上代码

/**
 * Created by baron on 2017/2/9.
 */
public class SearchView extends AutoCompleteTextView {
    private Drawable mDrawableRight;
    private Rect mBounds;
    private BtnListener mBtnListener;
    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
        if (right != null) {
            mDrawableRight = right;
        }
        super.setCompoundDrawables(left, top, mDrawableRight, bottom);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && mDrawableRight != null) {
            mBounds = mDrawableRight.getBounds();

            final int x = (int) event.getX();
            final int y = (int) event.getY();

            if (x >= (this.getWidth() - mBounds.width()) && x <= (this.getWidth() - this.getPaddingRight())
                    && y >= this.getPaddingTop() && y <= (this.getHeight() - this.getPaddingBottom())) {
                if(mBtnListener!=null){
                    mBtnListener.onClick();
                }
                event.setAction(MotionEvent.ACTION_CANCEL);
            }
        }
        return super.onTouchEvent(event);
    }
    public void setBtnListener(BtnListener btnListener){
        mBtnListener=btnListener;
    }
    public interface BtnListener{
        void onClick();
    }
}
为了能够获取点击事件,我们需要重载onTouchEvent方法,然后判断是否点击了对应的图片(按钮),当点击事件发生时,调用接口实例的点击事件(使用者可自定义)。

使用 在XML中

<com.baron.androidutilb.view.SearchView
        android:id="@+id/searchview"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:drawableRight="@mipmap/icon_search"/>
在 Java代码中设置
        SearchView mSearchView=(SearchView)findViewById(R.id.searchview);
        ArrayAdapter<String> marrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[]{"lijiaqiang", "liujiaqiang", "xujing", "lijing"});
        mSearchView.setAdapter(marrAdapter);
        mSearchView.setBtnListener(new SearchView.BtnListener() {
            @Override
            public void onClick() {
                ToastUtils.showToast_Now("你点击了搜索",MainActivity.this);
            }
        });
使用效果



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值