How to finish parent activity from child activity

戏子无情 提交于 2019-12-20 09:49:36

问题


I am new to Android development.

I have created a main Activity (->A), which has 4 buttons. One of the 4 buttons is the EXIT-button.

I start another activity (->B), on click of the EXIT-button. This opens 'B'Activity via an intent from 'A'Activity.

Activity 'B' contains - Do you want to exit? Yes-Button & No-Button.

If I give finish(), onclick of the button - it exits the 'B'Activity. I want to finish 'B' & 'A'.

I have even tried A.finish() -> this doesn't get recognized and results in syntax/semantic error.

I would appreciate help here.

P.S : I am using Android-2.2 version phone, and I do not like to use ActivityManager to resolve this.


回答1:


Try to launch child activity with

 startActivityForResult(intent, REQUEST_EXIT);

In child activity

case R.id.quit:
     setResult(RESULT_OK, null);
     finish();

In parent activity

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_EXIT) {
         if (resultCode == RESULT_OK) {
            this.finish();

         }
     }
}



回答2:


use startActivityForResult() in Activity A for start activity B and onActivityResult() in A just finish() Activity A. In Activity B on Button pressed just finish() Activity B.




回答3:


You can finish parent activity from child activity like...

In Parent....

 startActivityForResult(new Intent(Parent.this, Child.class), ACTIVITY_CONSTANT);

And override the OnActivityForResult(...) method in Parent .

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == ACTIVITY_CONSTANT)
    {
        finish();
    }
}

When you call finish() on child activity, it finishes parent also.



来源:https://stackoverflow.com/questions/9664108/how-to-finish-parent-activity-from-child-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!