Android覆盖onBackPressed()以发送意图

时间:2015-04-07 12:33:05

标签: android

我试图覆盖onBackPressed()以便像这样的意图将数据发送到上一个屏幕;

    thisUserObj = (User) getIntent().getSerializableExtra("UserObj");


    Intent intent = new Intent();
    intent.putExtra("UserObj", thisUserObj);
    setResult(RESULT_OK, intent);

但是当按下按钮时,UserObj值为null,但是这可以从onClickListener

开始
    Intent intent = new Intent(getApplication(), MainMenuActivity.class);
    intent.putExtra("UserObj", thisUserObj);
    startActivity(intent);

2 个答案:

答案 0 :(得分:5)

startActivity(intent)。要在onActivityResult()中获得结果,结果应为startActivityForResult()

答案 1 :(得分:0)

第一项活动中的

public static final int REQUEST_CODE = 100;
....

Intent intent=new Intent(MainActivity.this, MainMenuActivity.class);
intent.putExtra("UserObj", thisUserObj);  
startActivityForResult(intent, REQUEST_CODE); 


// still in first activity 

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
         // do your stuff here            

        }
    }
}

在您的案例MainMenuActivity类

中的第二个活动中
thisUserObj = (User) getIntent().getSerializableExtra("UserObj");

Intent intent = new Intent();
intent.putExtra("UserObj", thisUserObj);
setResult(RESULT_OK, intent);
finish();

覆盖后退按钮

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
       //Things to Do
        return true;
    }
    return super.onKeyDown(keyCode, event);
}