我尝试使用搜索字段实现操作栏,基于官方的android tuto(http://developer.android.com/training/search/setup.html)
这是我的档案:
清单文件:
<application
...
android:theme="@style/Theme.AppCompat.Light" >
<activity
android:name=".activities.MainActivity"
android:label="@string/title_activity_main" >
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<activity
android:name=".activities.SearchActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
...
</application>
(元数据存在)
MainActivity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_menu, menu);
//Searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); //MenuItemCompat.
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
action_bar_menu.xml:
<item
android:id="@+id/search"
android:icon="@drawable/ic_action_search"
android:title="@string/menu_search"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
yourapp:showAsAction="always"/>
RES / XML / searchable.xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="my hint"
android:label="@string/app_name" />
显示操作栏及其搜索按钮。我可以输入数据但是当点击搜索按钮(虚拟键盘)时,没有任何附加内容。
有什么想法吗? 谢谢
答案 0 :(得分:1)
使用此代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_sky_reader_android, menu);
SearchView mSearchView = (SearchView) menu.findItem(R.id.menu_search);
setupSearchView(mSearchView);
return true;
}
private void setupSearchView(final MenuItem searchItem) {
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW );
mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return true;
}
});
}
答案 1 :(得分:1)
可搜索的标签应与活动中的标签相同,请尝试此
清单中的
<activity
android:name=".activities.SearchActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:label="@string/app_search"
android:windowSoftInputMode="stateHidden" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
在可搜索的
中<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="my hint"
android:label="@string/app_search" />
希望它有效