在项目中经常的一个需求是监听用户输入的内容变化,然后做响应。
1.首先的想到的一个监听回调肯定是
addTextChangedListener()该方法可以监听到EditText中的所有的文字的变化,只要调用setText或者用户输入就响应。
2.肯定是setOnFocusChangeListener()该方法可以监听当前控件的焦点变化
如何自如地控制着两者呢,用到一个标记,以及两个方法,具体代码如下:
mSearchEt.requestFocus(); //监听输入文字变化请求后台 mSearchEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mIsEtFocused) { //当文字内容变化就请求后台 if (s.length() > 0) { mKeyword = s.toString(); startLoading(); //请求联想搜索 mNovelPresenter.novelSearchImagine(mKeyword); mNovelSearchImagineAdapter.setSearchText(mKeyword); mClearInputIb.setVisibility(View.VISIBLE); mSearchIv.setVisibility(View.GONE); } else { hideLoading(); mSearchResultRl.setVisibility(View.VISIBLE); mSearchResultNoBookRl.setVisibility(View.GONE); mSearchIv.setVisibility(View.VISIBLE); mClearInputIb.setVisibility(View.GONE); mNovelSearchImagineBeanList.clear(); mSearchHistoryLl.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); } } } @Override public void afterTextChanged(Editable s) { } }); /** * 监听当前是否有焦点 */ mSearchEt.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { mIsEtFocused = true; } else { mIsEtFocused = false; } } });
mSearchEt.clearFocus();上面这个方法是重点,查看源码发现并不是单纯得清空当前的焦点,而是清空并重新置位当前界面的第一个控件。
/** * Called when this view wants to give up focus. If focus is cleared * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. * <p> * <strong>Note:</strong> When a View clears focus the framework is trying * to give focus to the first focusable View from the top. Hence, if this * View is the first from the top that can take focus, then all callbacks * related to clearing focus will be invoked after which the framework will * give focus to this view. * </p> */ public void clearFocus() { if (DBG) { System.out.println(this + " clearFocus()"); } clearFocusInternal(null, true, true); }此处的技巧是设置当前的EditText的直接父容器可以获取焦点,代码如下:
用这两个结合就可以轻松处理焦点以及内容变化并作出响应。
还有软键盘的控制:
mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//隐藏软键盘 mInputManager.hideSoftInputFromWindow(mSearchEt.getWindowToken(), 0);
<activity android:name=".novel.view.activity.NovelSearchActivity" android:screenOrientation="portrait" android:windowSoftInputMode="stateVisible|adjustPan"/>