MVP + Rxbinding + AutoCompleteTextView 实现关键词联想功能

只写与AutoCompleteTextView有关的代码:

一,View部分

public class SearchViewActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, GoodContract.IGoodView {
    @BindView(R.id.goodlistRecycle)
    RecyclerView goodlistRecycle;
    @BindView(R.id.tv_keyword)
    TextView tv_keyword;
    @BindView(R.id.srl_goodlist)
    SwipeRefreshLayout srl_goodlist;
    @BindView(R.id.et_search)
    AutoCompleteTextView et_search;
    @BindView(R.id.iv_close)
    ImageView iv_close;
    
    private ArrayAdapter mCompAdapter;
    private List goodEntities = new ArrayList();
    private RecyclerGoodAdapter mGoodAdapter;
    private String mKeyword = "";
    private List mStringKeyWord = new ArrayList();
    private Handler mHandler = new Handler();
    
    @OnClick(R.id.backTo)
    public void backto(){ finish(); }
    
    @Override
    protected GoodPresenter createPresenter() {
        return new GoodPresenter(this);
    }

    @Override
    public void showLoading() {
        //重写此方法,避免输入关键词后,页面刷新导致自动完成输入框下拉框消失
        int i = 0;
    }

    @Override
    public void hideLoading() {
        //重写此方法,避免输入关键词后,页面刷新导致自动完成输入框下拉框消失
        int i = 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_view;
    }

    @Override
    protected void initData() {
        srl_goodlist.setOnRefreshListener(this);
        srl_goodlist.setColorSchemeResources(
                R.color.red, R.color.orange, R.color.green, R.color.blue);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        goodlistRecycle.setLayoutManager(manager);
        goodlistRecycle.setItemAnimator(new DefaultItemAnimator());
        goodlistRecycle.addItemDecoration(new SpacesItemDecoration(1));
        
        //隐藏输入法,清除搜索内容,清除焦点
        RxView.clicks(iv_close).subscribe(o -> {
            DisplayUtil.hideOneInputMethod(this,et_search);
            et_search.setText("");
            et_search.clearFocus();
        });
        
        //控制iv_close
        RxTextView.textChanges(et_search).subscribe(charSequence -> {
            if (!TextUtils.isEmpty(charSequence)){
                iv_close.setVisibility(View.VISIBLE);
            } else {
                iv_close.setVisibility(View.GONE);
            }
        });

       et_search.setOnEditorActionListener((v, actionId, event) -> {
            if(actionId == EditorInfo.IME_ACTION_SEARCH){
                if (et_search.getText() != null){
                    mKeyword = et_search.getText().toString().trim();
                }
                DisplayUtil.hideAllInputMethod(SearchViewActivity.this);
                if (mKeyword.equals("")){return false;}
                mPresenter.searchByKeyWord("%" + mKeyword + "%");
                return true;
            }
            return false;
        });

        mCompAdapter = new ArrayAdapter(this, R.layout.search_list_auto,mStringKeyWord);
        et_search.setAdapter(mCompAdapter);
        et_search.setOnItemClickListener((parent, view, position, id) -> {
            //et_search.setText(((TextView) view).getText());
            mKeyword = ((TextView) view).getText().toString();
            DisplayUtil.hideAllInputMethod(SearchViewActivity.this);
            mPresenter.searchByKeyWord("%" + mKeyword + "%");
        });
        
        //关键词联想,向网站Api异步发送检索请求,调用Presenter中的方法
        RxTextView.textChanges(et_search)
                .debounce(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(charSequence -> charSequence.toString().trim().length() > 0)
                .subscribe(charSequence -> mPresenter.autoCompleteKey(charSequence.toString() + "%"));

    }

    private Runnable mRefresh = new Runnable() {
        @Override
        public void run() {
            srl_goodlist.setRefreshing(false);
            mPresenter.searchByKeyWord("%" + mKeyword + "%");
            goodlistRecycle.scrollToPosition(0);
        }
    };

    @Override
    public void onRefresh() {
        mHandler.postDelayed(mRefresh,2000);
    }

    @Override
    public void setStatus(int status, String info) {

    }

    @Override
    public void setAdapter(List goodEntityList) {
        mGoodAdapter = new RecyclerGoodAdapter(this,goodEntityList, WebApiContent::goodsDetail);
        goodlistRecycle.setAdapter(mGoodAdapter);
    }

    @Override
    public void setAdapter(List keyWordEntities, int i) {
        if (keyWordEntities.size() > 0){
            mStringKeyWord.clear();
            for (KeyWordEntity keyWordEntity : keyWordEntities) {
                mStringKeyWord.add(keyWordEntity.getGoodsSerachKeywords());
            }

            mCompAdapter = new ArrayAdapter(this, R.layout.search_list_auto,mStringKeyWord);
            et_search.setAdapter(mCompAdapter);
            mCompAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setAdapter(GoodEntity goodEntity) {

    }

    @Override
    public void showMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void onErrorCode(BaseModel model) {

    }

    @Override
    public void setData() {

    }
}

二,Presenter部分

public class GoodPresenter extends BasePresenterImpl {
    private GoodContract.IGoodView view;
    public GoodPresenter(GoodContract.IGoodView view) {
        super(view);
        this.view = view;
    }

    public void searchByKeyWord(String keyword){
        mWebApiService.searchByKeyWord(keyword)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver>(mView){
                    @Override
                    protected void onSucess(BaseModel> t) throws Exception {
                        view.setAdapter(t.getData());
                    } else {
                        view.showMsg(t.getMsg());
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.showMsg(e.getMessage());
                    }
                });
    }

    public void autoCompleteKey(String keyword){
        mWebApiService.autoCompleteKey(keyword)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver>(mView){
                    @Override
                    protected void onSucess(BaseModel> t) throws Exception {
                        if (t.isSuccess()){
                            view.setAdapter(t.getData(),0);
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        
                    }
                });
    }

}

你可能感兴趣的:(MVP + Rxbinding + AutoCompleteTextView 实现关键词联想功能)