永远不会调用Android onCreateOptionsMenu,因此不会显示菜单

时间:2017-07-07 16:52:08

标签: android menu android-appcompat android-search

我希望在菜单工具栏中有一个搜索栏,但是当我导航到该活动时,永远不会创建菜单,因为永远不会调用onCreateOptionsMenu。我正在扩展AppCompatActivity

-n

菜单:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return true;
}

1 个答案:

答案 0 :(得分:0)

问题可能在您的AndroidManisfest.xml文件上。使用以下默认代码,我将加载onCreateOptionsMenu(Menu menu)方法:

AndroidManisfest.xml:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d("BugFix","nothing");
        getMenuInflater().inflate(R.menu.menu_search, menu);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        return true;
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.el_greeko.exampleproject.MainActivity">

</android.support.constraint.ConstraintLayout>

其余的是您提供的信息,res / menu /

中的menu.search.xml

顺便说一下。我建议阅读网页上的说明 Search dialog。它还可以为您的搜索活动提供更好的解决方案。