工具栏操作触发设置菜单

时间:2015-08-07 18:48:34

标签: android android-fragments oncreateoptionsmenu

我有一个工具栏,其中包含一个附加到3点菜单的典型设置活动。

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

这是我如何在我的主要活动中调用我的设置

@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,并希望这是相当微不足道的感谢任何和所有的帮助

1 个答案:

答案 0 :(得分:3)

您的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);
}