我需要创建操作栏搜索视图,但我无法处理搜索项。
这是我的菜单xml项目:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
我重写onOptionsItemSelected方法来处理项目:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
System.out.println("press search");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
这是我的AndroidManifest:
<meta-data
android:name="android.app.default_searchable"
android:value=".app.Search" />
<activity android:name="com.example.tutorial_search_actionBar.MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</intent-filter>
</activity>
但是当我按下操作栏中的搜索项时1.my键盘没有搜索键 2.不打印“按搜索”
我该怎么办
答案 0 :(得分:0)
试试这个
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourAppName="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_action_search"
yourAppName:showAsAction="ifRoom|collapseActionView"
yourAppName:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_xml, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
final int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
menuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
getLoaderManager().initLoader(1, null, YourClass.this);
return true; // Return true to collapse action view
}
});
} else {
MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
getLoaderManager().initLoader(1, null, YourClass.this);
return true;
}
});
}
searchView.setIconifiedByDefault(true);
}