Unable to finish activity from onOptionsItemSelect

2020-04-18 05:53发布

问题:

I am trying to close the Activity from menu option. When menuItem menu_close_activity is selected, (and while debugging) I noticed that debugger always jumps from return true step to default. I tried to use ActivityClassName.this.finish(), but I am still getting the same results

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_xxxx:
                break;
            case R.id.menu_yyyy:
                break;
            case R.id.close_activiy:
                // doing some stuff here;
                setResult(0001);
                finish();    // Debugger jumps from here
                return true;
            default:
                return super.onOptionsItemSelected(item); // Debugger jumps to here.
        }
    }

Why I am jumping to default, and not going to return true?


Beside this method I have public boolean onCreateOptionsMenu(Menu menu) doing nothing but inflating the options menu, and protected void onCreate(Bundle savedInstanceState)

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name_list);
        Bundle b = getIntent().getExtras();
        name = b.getString("name");
        setTitle("Students of " + name);
    }

回答1:

I don't see the reason why you activity is not finishing. It should. Could you add some logs to onDestroy() method and see it's getting called.

As to why the Debugger is Jumping, well, don't trust the debugger in this case. I think it jumps because of different stuff happening in different threads. Instead add some logs to see what actually happens. Replace your code with the following and check the logs.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_xxxx:
            break;
        case R.id.menu_yyyy:
            break;
        case R.id.close_activiy:
            // doing some stuff here;
            Log.d("DEBUG","BEFORE FINISH = "+item.toString());
            setResult(1);
            finish();    // Compiler jumps from here
            Log.d("DEBUG","AFTER FINISH = "+item.toString());
            return true;
        default:
            Log.d("DEBUG","DEFAULT STATEMENT = "+item.toString());
            return super.onOptionsItemSelected(item); // Compiler jumps to here.
    }
}