您的位置:首页 > 移动开发 > Android开发

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

2017-02-09 11:14 1081 查看
  在开发中,输入框和搜索框是我们非常频繁的用到的控件,针对输入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);
}
});
使用效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐