Search code examples
androidandroid-recyclerviewshared-element-transition

How to transition from activity 3rd to 1st?


I have a problem with Shared Element Activity Transition between activities. I have MainActivity, it has a recyclerview with boxes (recyclerview.horizontal). Each box when clicked will go to the corresponding activity. The problem that appears when I click on a box, I switch to the second activity, in the second activity I press a button to switch to the third activity. And here I swipe to right to return to the MainActivity with transition and I want it to transition right to the box corresponding to the 3rd activity in the recyclerview in MainActivity. So, my purpose is:

MainActivity (Shared Element Activity Transition)-> Second Activity -> Third Activity (Shared Element Activity Transition)-> MainActivity (exactly scroll to position for Third Activity in RecyclerView).

My MainActivity I hope everyone offer me the solution. Thank you so much.


Solution

  • You can use startActivityForResult instead of startActivity in SecondActivity when you are going to start ThirdActivity.Like this :

    Intent i = new Intent(this, ThirdActivity.class);
    startActivityForResult(i, 1);
    

    And when you are finishing your ThirdActivity

    Intent returnIntent = new Intent();
    returnIntent.putExtra("activity_finish",true);
    setResult(Activity.RESULT_OK,returnIntent);
    finish();
    

    If you use startActivityForResult() then it gives callback in the Activity who started it,so as soon as ThirdActivity finishes, it will return to the onActvityResult() in SecondActivity.Where you have to check result_code and request code like this :

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            boolean isActivityFinish=data.getBooleanExtra("activity_finish");
             if(isActivityFinish){
              // finish your Second Activity here
              }
    
    
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
    

    }

    For more info : How to manage `startActivityForResult` on Android?