在开发中,输入框和搜索框是我们非常频繁的用到的控件,针对输入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); } });使用效果
新闻热点
疑难解答