我使用的是Android 4.1.2。我在ActionBar
上有一个SearchView小部件。来自android开发者网站的SearchView.OnQueryTextListener
上的文档指出,当用户提交查询时调用onQueryTextSubmit
。这可能是由于键盘上的按键或按下提交按钮。 “
如果搜索查询为空,则不会发生这种情况。我需要这个来触发一个空查询来清除ListView的搜索过滤器。这是一个错误还是我做错了什么?
答案 0 :(得分:14)
这不是一个错误,source code故意检查空值和空值:
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if (query != null && TextUtils.getTrimmedLength(query) > 0) {
但是,当用户清除搜索EditText时,您应该能够使用OnQueryTextChange回调清除ListView的过滤器。
答案 1 :(得分:12)
我更容易解决: 使用onQueryTextChange,但只有在其为空时才会呈现。
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
renderList(true);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (searchView.getQuery().length() == 0) {
renderList(true);
}
return false;
}
});
答案 2 :(得分:10)
我遇到了同样的问题并最终得到了以下解决方案:自定义SearchView
+ OnQueryTextListener.onQueryTextChange
自定义SearchView:
public class MySearchView extends SearchView {
private boolean expanded;
public MySearchView(Context context) {
super(context);
}
@Override
public void onActionViewExpanded() {
super.onActionViewExpanded();
expanded = true;
}
@Override
public void onActionViewCollapsed() {
super.onActionViewCollapsed();
expanded = false;
}
public boolean isExpanded() {
return expanded;
}
}
创建动作并设置回调:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
searchAction = menu.add(0, SEARCH_ACTION_ID, 0 , getString(R.string.action_search));
searchAction.setShowAsAction(SHOW_AS_ACTION_ALWAYS | SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
searchView = new MySearchView(getSherlockActivity());
searchView.setOnQueryTextListener(searchQueryListener);
searchView.setIconifiedByDefault(true);
searchAction.setActionView(searchView);
}
最后听众:
private OnQueryTextListener searchQueryListener = new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
search(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (searchView.isExpanded() && TextUtils.isEmpty(newText)) {
search("");
}
return true;
}
public void search(String query) {
// reset loader, swap cursor, etc.
}
};
在ABS 4.3上测试。
答案 3 :(得分:9)
我在SearchView上遇到了同样的问题。我的解决方案包括样式SearchView,如指南http://novoda.com/blog/styling-the-actionbar-searchview/所示,并为EditText设置OnEditorActionListener(How do I trigger an action when the user has hit enter?),这是SearchView的一部分:
final SearchView searchView = (SearchView)findViewById(R.id.search);
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchPlate = (EditText) searchView.findViewById(searchPlateId);
searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//Do something
}
return false;
});
答案 4 :(得分:3)
正如其他人所说,这种行为是故意的。我放弃了OnQueryChangeListener
的解决方案,并决定通过在SearchView的OnEditorActionListener
上实施EditText
来解决这个问题,您可以使用R.id.search_src_text
来处理问题。只要您setImeOptions
的SearchView EditorInfo.IME_ACTION_SEARCH
,您就可以点击键盘搜索按钮。有关详细信息,请参阅this SO answer。
答案 5 :(得分:1)
我遇到了同样的问题,因为不支持空查询我必须下载并使用ActionBarSherlock然后修改onSubmitQuery()方法。
这就是我的onSubmitQuery()现在的样子
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if (query == null) {query = "";}
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
setImeVisibility(false);
}
dismissSuggestions();
}
}
希望这有帮助。
答案 6 :(得分:0)
您无法覆盖此行为。 当用户退出搜索视图时,解决方法可能是清除过滤器。
您可以使用OnCloseListener。 但是,这也会导致问题,具体取决于您正在开发的最低API级别。
答案 7 :(得分:0)
另一种选择是通过TextWatcher手动触发onQueryTextChange方法:
public class MyActivity extends Activity implements SearchView.OnQueryTextListener, TextWatcher {
// Basic onCreate(Bundle) here
@Override
public boolean onCreateOptionsMenu (final Menu menu) {
getMenuInflater().inflate(R.menu.myMenu, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
final SearchManager manager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
final int resource_edit_text = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
((EditText) searchView.findViewById(resource_edit_text)).addTextChangedListener(this);
return super.onCreateOptionsMenu(menu);
}
// Implementation of TextWatcher, used to have a proper onQueryTextChange (it doesn't update when the last character is removed)
@Override
public void beforeTextChanged (final CharSequence charSequence, final int start, final int count, final int after) {}
@Override
public void onTextChanged (final CharSequence charSequence, final int start, final int before, final int after) {}
@Override
public void afterTextChanged (final Editable editable) {
if (editable.length() == 0)
onQueryTextChange(editable.toString());
}
// Implementation of OnQueryTextChangeListener
@Override
public boolean onQueryTextChange (final String query) {
// do stuff
return false;
}
@Override
public boolean onQueryTextSubmit (final String query) {
// do stuff
return false;
}
}
这一切都与这里放弃的所有默认xml文件一致,这不是这个答案的重点。这是我选择使用的解决方法,随意使用其他人
答案 8 :(得分:0)
我可以通过以这种方式实现setOnQueryTextListener来实现:
SearchView searchView = (SearchView) menu.findItem(R.id.searchProductView).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
loadLocalData(newText);
}
return true;
}
});
我的loadLocalData方法是
//query my DB
products = ProductDAO.findByIdList(idList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
listView.setAdapter(<YOURADAPTER>)
即使您使用&#34; X&#34;清除文本,此解决方案也会清除您的查询。按钮
答案 9 :(得分:0)
在我的情况下,我只是想让用户清除他的查询,因为它在API搜索中用作关键字,所以最简单的想法是:
searchView.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
userQuery = "";
}
});
其中userQuery是我用于搜索等的变量。
希望它可以帮助某人:)
答案 10 :(得分:0)
这是一个旧线程,但是我找到了另一个解决方案(Kotlin代码,但也可以在Java中工作):
override fun onQueryTextChange(newText: String?): Boolean {
if(newText == null || newText.isEmpty())
searchView.setQuery("\u00A0", false)
return true
}
\u00A0
是一个看起来像空格的字符,但就代码而言却不是。换句话说,SearchView不为空。空字符串或" "
将不起作用,因为基本SearchView使用修剪,而且用户可能希望搜索以空格结尾或开头的文本。但据我所知,用户无法输入\u00A0
字符。
然后您要做的就是在自定义SearchView中将getQuery覆盖为return super.getQuery.replace("\u00A0", "")
答案 11 :(得分:0)
这是用Kotlin编写的完整示例:
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.appcompat.widget.SearchView
/**
* Custom [SearchView] which can listen to empty submit events
*
* If the internal implementation would change, this will not crash at runtime. It will simply
* ignore the empty submit listener and will continue to work as this is the base [SearchView]
*/
class EmptySubmitSearchView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : SearchView(context, attrs, defStyleAttr) {
private lateinit var searchAutoComplete: SearchAutoComplete
private lateinit var internalEditorListener: TextView.OnEditorActionListener
private var emptySubmitListener: OnEmptySubmitListener? = null
init {
try {
val defaultListenerField = SearchView::class.java
.getDeclaredField("mOnEditorActionListener")
defaultListenerField.isAccessible = true
internalEditorListener = defaultListenerField.get(this) as TextView.OnEditorActionListener
val searchAutoCompleteField = SearchView::class.java
.getDeclaredField("mSearchSrcTextView")
searchAutoCompleteField.isAccessible = true
searchAutoComplete = searchAutoCompleteField.get(this) as SearchAutoComplete
searchAutoComplete.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE && TextUtils.isEmpty(searchAutoComplete.text)) {
emptySubmitListener?.onEmptyTextSubmit()
} else {
internalEditorListener.onEditorAction(v, actionId, event)
}
true
}
} catch (ignored: Exception) {
//Some internal field has changed. Check there is a field called
//mSearchSrcTextView and mOnEditorActionListener and if not update them accordingly
}
}
/**
* Set custom empty listener or null to remove it
*/
fun setOnEmptySubmitListener(listener: OnEmptySubmitListener?) {
emptySubmitListener = listener
}
interface OnEmptySubmitListener {
fun onEmptyTextSubmit()
}
}
您可以使用setOnEmptySubmitListener
设置自定义侦听器,这将使您能够区分事件。
您可以自定义要响应的actionId,在这种情况下,我在XML中使用了android:imeOptions="actionDone|flagNoExtractUi"
答案 12 :(得分:0)
这是 samvel1024 的答案,将其转换为 Kotlin。 您可能需要将 IME_ACTION_GO 更改为您用于键盘“开始”按钮的任何内容。只需在页面初始化期间运行此方法。
/**
* Business: User should be allowed to perform an empty search.
* SearchView does not cause OnQueryTextChange to fire when the box is empty.
* To create a listener method for this scenario, we use reflection to gain access to the SearchView's inner TextView.
*/
private fun enableEmptySearch(searchView: SearchView) {
try {
val searchViewClass = searchView::class.java
val currentListenerField: Field = searchViewClass.getDeclaredField("mOnEditorActionListener")
currentListenerField.isAccessible = true
val previousListener: TextView.OnEditorActionListener = currentListenerField.get(searchView) as TextView.OnEditorActionListener
val newListener: TextView.OnEditorActionListener = TextView.OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_GO && v.text.isEmpty()) {
querySubmit()
}
previousListener.onEditorAction(v, actionId, event)
}
val innerTextViewField: Field = searchViewClass.getDeclaredField("mSearchSrcTextView")
innerTextViewField.isAccessible = true
(innerTextViewField.get(searchView) as TextView).setOnEditorActionListener(newListener) // Allow user to tap the "GO" button when the SearchView is empty.
} catch (ignored: Exception) {
// If a major change occurs to android SDK, internal fields mSearchSrcTextView or mOnEditorActionListener might not exist.
// This exception will prevent this additional feature from functioning, but not crash the app or cause any other issues.
}
}