setResult does not work when BACK button pressed

前端 未结 10 1885
南方客
南方客 2020-11-27 13:08

I am trying to setResult after the BACK button was pressed. I call in onDestroy

Intent data = new Intent();
setResult(RESULT_OK, data) 

But

相关标签:
10条回答
  • 2020-11-27 13:54

    If you want to set some custom RESULT_CODE in onBackPressed event then you need to first set the result and then call the super.onBackPressed() and you will receive the same RESULT_CODE in the caller activity's onActivityResult method

        @Override
        public void onBackPressed()
        {
             setResult(SOME_INTEGER);
             super.onBackPressed();
        }
    
    0 讨论(0)
  • 2020-11-27 13:54

    You should override onOptionsItemSelected like this:

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            final Intent mIntent = new Intent();
            mIntent.putExtra("param", "value");
            setResult(RESULT_OK, mIntent);
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:58

    I refactored my code. Initially I prepared some data and set it as activity result in onDestroy (this did not work). Now I set activity data each time the data to be returned is updated, and have nothing in onDestroy.

    0 讨论(0)
  • 2020-11-27 14:00

    Refer onActivityResult(int, int, Intent) doc

    Solution is to check the resultCode for value Activity.RESULT_CENCELED. If yes, then it means that either BACK was pressed or the activity crashed. Hope it works for you guys, works for me :).

    0 讨论(0)
提交回复
热议问题