我有一个活动,可以完美地显示标题栏中的搜索,但是现在我想将在搜索操作栏中输入的文本输入到字符串中。请帮忙!
她是我的menu / xml
<?xml version="1.0" encoding="utf-8"?>
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"
/>
</menu>
她是onCreate中的代码
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
答案 0 :(得分:3)
您使用过searchView
吗?您可以使用以下代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
.getActionView();
if (null != searchView) {
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
// This is your adapter that will be filtered
return true;
}
public boolean onQueryTextSubmit(String query) {
// **Here you can get the value "query" which is entered in the search box.**
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
答案 1 :(得分:1)
如果您使用的是工具栏,则可以执行此操作:
MenuItem menuItem = getToolbar().getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.i("well", " this worked");
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.i("well", " this worked");
return false;
}
});