这可以视为此Question
的扩展我在代码中添加了以下内容以获取searchView Widget
RES /菜单/ main_activity_actions.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="always"
android:actionViewClass="android.support.v7.widget.SearchView" />
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>
Mainactivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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.main_activity_actions, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
System.out.println("TESTING: "+searchView);
return super.onCreateOptionsMenu(menu);
}
---
---
}
该应用程序显示正常但触摸搜索按钮时没有显示任何内容。
按如下方式设置Sdk版本:(4.0.3 -4.2.2)
android:minSdkVersion="15"
android:targetSdkVersion="17"
答案 0 :(得分:15)
将菜单更改为,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
yourapp:showAsAction="always" />
</menu>
答案 1 :(得分:0)
您的菜单中缺少“collapseActionView”:
app:showAsAction="ifRoom|collapseActionView"