工具栏操作触发设置菜单

toolbar actions triggering settings menu

我有一个带有典型设置的工具栏 activity 附加到 3 点菜单。

在我的一个片段中,我更改了工具栏以添加几个图标,但是当按下这些图标时,它会运行其方法,然后启动典型设置 activity、

这里是我如何在主 activity

中调用我的设置
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem mItem) {
    // 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 = mItem.getItemId();
    Intent intent = new Intent(MainActivity.this, Settings.class);
    startActivity(intent);

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

    return super.onOptionsItemSelected(mItem);
}

这是我添加项目并在我的片段中使用它们的方式

@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    // Inflate the menu items for use in the action bar

    inflater.inflate(R.menu.set_menu, menu);

    mShare = menu.findItem(R.id.share);
    mSave = menu.findItem(R.id.save);

    super.onCreateOptionsMenu(menu, inflater);

}

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.share:
             share();
            break;

        case R.id.save:
            saveWallpaper();

            return true;
        default:
    }
    return true;
}

我对 android 还是有点陌生​​,希望这是相当微不足道的感谢所​​有帮助

您的 onOptionsItemSelected() 无条件调用 startActivity(),而不是仅在选择“设置”选项时调用它。在 if 语句中移动这些行:

@Override
public boolean onOptionsItemSelected(MenuItem mItem) {
    // 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 = mItem.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent intent = new Intent(MainActivity.this, Settings.class);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(mItem);
}