4

这可以被认为是这个问题的扩展

我在代码中添加了以下内容以获取 searchView Widget

res/menu/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"
4

2 回答 2

16

将您的菜单更改为,

<?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>
于 2013-11-29T17:04:53.007 回答
0

您的菜单中缺少“collapseActionView”:

app:showAsAction="ifRoom|collapseActionView"
于 2015-07-19T12:00:42.577 回答