Reputation: 329
Let say there 3 activities :
Activity A
Activity B
Activity C
Then on Activity C, there is a button FinishButton
So, the behavior that I want on Activity C is that :
1. If I press back button , the Activity C will get closed then we will see the Activity B (just like normal behavior)
2. If I press FinishButton , the Activity B and Activity C will get closed then we will see the Activity A
Is there a way to do this ?
I do some research but only to find a way to close all previous activities.
Upvotes: 0
Views: 52
Reputation: 24907
You can use combination of startActivityForResult
and setResult()
.
When you start Activity C, start it using startActivityForResult
and in Activity C set the result to RESULT_CANCELED
. Check this flag in Activity B. If its OK, then don't do anything, but if its RESULT_CANCELED
then just finish Activity B.
you can implement it as follows:
ActivityB.java
public class ActivityB extends AppCompatActivity{
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
//initialize btn;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(ActivityB.this,ActivityC.class),100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100){
if(resultCode == RESULT_OK){
//Do nothing
} else if (resultCode == RESULT_CANCELED) {
finish();
}
}
}
}
ActivityC.java
public class ActivityC extends AppCompatActivity{
Button btnFinish;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
//initialize btnFinish;
btnFinish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setResult(RESULT_CANCELED);
finish();
}
});
}
@Override
public void onBackPressed() {
setResult(RESULT_OK);
finish();
}
}
Upvotes: 2