Android OnOptions ItemSelected未在AppActivity中调用setDisplayHomeAsUpEnabled的片段

Android OnOptions ItemSelected未在AppActivity中调用setDisplayHomeAsUpEnabled的片段,android,fragment,appcompatactivity,Android,Fragment,Appcompatactivity,我在stackoverflow搜索了一整天所有类似的问题和答案,但没有找到它为什么不起作用的线索 这里是我代码的一些摘录 片段: public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_galler

我在stackoverflow搜索了一整天所有类似的问题和答案,但没有找到它为什么不起作用的线索

这里是我代码的一些摘录

片段:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
    setHasOptionsMenu(true);
    actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    actionBar.setTitle("Portfolio");
    updateGallery();
    return rootView;
}


    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
}

    public void updateGallery() {
    if (activeAlbum>0) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    } else {
        actionBar.setDisplayHomeAsUpEnabled(false);
    }
 ......
}

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        default:
            break;
    }
    return false;
}
主要活动:

public class MainActivity extends AppCompatActivity {...}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

....

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


......
 }


    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

OnOptions ItemSelected在MainActivity和Fragment中均未激发。Fragment必须声明它们可以提供选项。请看这里:


我想您只需要在片段的onCreateView()中调用setHasOptionsMenu(true)。

谢谢您的链接,我会看一看(我已经在调用setHasOptionsMenu(true))我担心其他东西可能会干扰onOptionsItemSelected(也许我应该尝试添加一个新的“空”片段进行测试)