我正在尝试将搜索视图添加到Android中的应用栏。接下来是本教程:http://developer.android.com/training/search/setup.html#add-sv
但是当我运行程序时,只能点击一个图标,搜索视图没有出现,但是教程说它应该出现。任何人都可以帮助我吗?
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search"
android:title="@string/abc_search_hint"
android:icon="@drawable/ic_search_white_48dp"
app:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.widget.SearchView" />
</menu>
MainActivity
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
return true;
}
答案 0 :(得分:1)
XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/search"
android:title="@string/search"
android:icon="@drawable/ic_search_white"
android:textColor="@color/white"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
活动
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
if (mSearchTerm == null && newFilter == null) {
return true;
}
if (mSearchTerm != null && mSearchTerm.equals(newFilter)) {
return true;
}
mSearchTerm = newFilter;
mSearchQueryChanged = true;
searchText(newText); //handle this
return true;
}
});
MenuItemCompat.OnActionExpandListener expandListener = new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
return true;
}
};
MenuItemCompat.setOnActionExpandListener(searchItem, expandListener);
return super.onCreateOptionsMenu(menu);
}