我想在我的Android应用中使用搜索视图。为此,我在app_bar中添加了searchview:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColorDark">
<SearchView
android:id="@+id/mySearchView"
android:icon="@drawable/ic_magnify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:iconifiedByDefault="true"
android:queryHint="Search from Qur'an"/>
</android.support.v7.widget.Toolbar>
现在,实现此目的的方法是:
search = (SearchView) findViewById(R.id.mySearchView);
search.setQueryHint("SearchView");
//*** setOnQueryTextFocusChangeListener ***
search.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), String.valueOf(hasFocus) +" I am in has focus",
Toast.LENGTH_SHORT).show();
}
});
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),SearchResultsActivity.class));
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), newText,
Toast.LENGTH_SHORT).show();
return false;
}
});
现在,我想添加下拉列表,如下所示:
现在,在点击任何这些项目时,应启动一项新活动。我怎样才能做到这一点。另外,我是Android开发的新手,所以请建议我使用其他任何方法。
编辑1:
使用setOnSuggestionListener不起作用:
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return true;
}
@Override
public boolean onSuggestionClick(int i) {
//your intent
startActivity(new Intent(getBaseContext(),SearchResultsActivity.class));
return true;
}
});
答案 0 :(得分:1)
只需在suggestionListener上实现
以下代码是可以帮助您的简短示例
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return true;
}
@Override
public boolean onSuggestionClick(int i) {
//your intent
return true;
}
});