简体   繁体   English

使用“ onBackPressed()”使开始的活动返回到先前的屏幕

[英]Making an activity which started itself go back to previous screen with “onBackPressed()”

I have an activity which is repeated "x" times with this piece of code : 我有一段这段代码重复“ x”次的活动:

//create intent to start itself again with different parameters
            Intent intent = getIntent();

            intent.putExtra(CATEGORY_ID, temp.getCat_ID());
            intent.putExtra(CATEGORY_SHOPID, temp.getShopID());
            intent.putExtra(CATEGORY_SITEID, temp.getSiteID());
            intent.putExtra(CATEGORY_NAME, temp.getCat_Name());

            finish();
            startActivity(intent);

My goal is that when the user presses the back button that the same activity gets started as there was before with the same parameters as before and such. 我的目标是,当用户按下“后退”按钮时,将使用与以前相同的参数开始与以前相同的活动。 I tried saving them in an Activity ArrayList but that doesn't seem to work. 我尝试将它们保存在Activity ArrayList中,但这似乎不起作用。

When you call finish, your activity will end. 通话结束时,您的活动将结束。 When you don't call finish, your activity just go to the background. 当您不打完电话时,您的活动只会转到后台。 In that case, when you press the backbutton in your new activity, your previous activity comes up. 在这种情况下,当您在新活动中按下后退按钮时,将显示先前的活动。

I think when you just delete finish(), it will work. 我认为当您只删除finish()时,它将起作用。

It's okay if you save the parameters you've already set earlier, but you need to retrieve all that information from the Intent itself and repopulate your activity with the proper data. 可以保存之前设置的参数,但是您需要从Intent本身中检索所有信息,并使用适当的数据重新填充您的活动。

This must be done like this: 必须这样完成:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String categoryId = getIntent().getStringExtra(CATEGORY_ID);

    // retrieve the others and populate your activity 

}

in your activity, get event back 在您的活动中,获取事件回来

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        // and you have to make a intent to call this activity again with parameter other
        finish(); // and call finish() here to close the old activity
    }
    return super.onKeyDown(keyCode, event);
}

hope this help! 希望对您有所帮助!

您是否尝试覆盖onBackPressed方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM