用于在Android上点击两个不同操作之间切换的菜单

时间:2017-07-12 15:25:33

标签: android button menu toggle

我正在尝试使菜单图标响应第一次单击时的两个不同操作应触发第二次单击同一菜单时的第一个操作触发另一个操作,再次单击时应该调用第一个操作就像在操作之间切换一样/ p>

方法

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int _clicks = 0;
    int count;

    switch (item.getItemId()) {

        case R.id.action_sort:
            count = ++_clicks;
            if (count == 1){
                Cursor cursor2 = databaseManager.queryAllInsects(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME +  " COLLATE NOCASE ASC");
                mAdapter.swapCursor(cursor2);
                return true;
            } if (count == 2){
                Cursor cursor3 = databaseManager.queryAllInsects(BugsContract.BugsEntry.COLUMN_DANGERLEVEL +  " COLLATE NOCASE DESC");
                mAdapter.swapCursor(cursor3);
                return true;
            }

        default:
            return super.onOptionsItemSelected(item);
    }

}

我实际上是这样做的,但是一旦它进入第二次点击,它就不会切换回第一个功能,即不能再次点击。任何人都可以帮助你。我最坚持使用操作栏菜单

2 个答案:

答案 0 :(得分:0)

为什么不尝试使用boolean

boolean b = false;

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(b) {
        // Do one thing.
    }
    else {
        // Do another.
    }
    // Invert the state of the boolean. (This will enter the other case next time.)
    b = !b;
}

如果您更喜欢使用整数,可以试用modulo运算符。通过将数字除以2,剩余部分可用于指示数字是奇数还是偶数。然后你可以按如下方式编写序列:

int x = 0;

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(((x++) % 2) == 0) { // Is the remainder equal to 0? (Even or Odd)
        // Do one thing.
    }
    else  {
       // Do another.
    }
}

答案 1 :(得分:0)

这样做:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int _clicks = 0;
int count;

switch (item.getItemId()) {

    case R.id.action_sort:
        count = ++_clicks;
        if (count == 1){
            Cursor cursor2 = databaseManager.queryAllInsects(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME +  " COLLATE NOCASE ASC");
            mAdapter.swapCursor(cursor2);
            return true;
        } if (count == 2){
            _clicks = 0;
            Cursor cursor3 = databaseManager.queryAllInsects(BugsContract.BugsEntry.COLUMN_DANGERLEVEL +  " COLLATE NOCASE DESC");
            mAdapter.swapCursor(cursor3);
            return true;
        }

    default:
        return super.onOptionsItemSelected(item);
}

}

这样,通过第二次单击,变量_click将具有值= 0,然后,通过第三次单击,将显示第一个操作。