How can one know if an activity is started without a transition?

前端 未结 2 984
走了就别回头了
走了就别回头了 2021-02-12 19:39

I have a use case where I mostly start an activity with a transition, but that\'s not the case when opening it from the navigation drawer.

To keep the transition smooth

2条回答
  •  失恋的感觉
    2021-02-12 20:40

    Since you are starting an Activity, you'll be making use of an Intent to start it. You can add extras to Intents and check for them in the onCreate() of the called Activity.

    Let's assume that we have 2 Activities – ActivityA, and ActivityB.

    Now, let's assume that ActivityA is the calling Activity, and that ActivityB is the called Activity.

    In ActivityA, let's say you've written some code to start ActivityB with a SharedElementTransition.

    @Override
    public void onClick(View v) {
        Intent startActivityBIntent = new Intent(getContext(), ActivityB.class);
        startActivityBIntent.putExtra("IS_SHARED_ELEMENT_TRANSITION_ENABLED", true);
        ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), view, ViewCompat.getTransitionName(view));
        startActivity(startActivityBIntent, activityOptionsCompat);
    }
    

    Now, if you notice above, I've passed an Intent extra with the putExtra() method. I've passed a Boolean value of true because I intend to start the Activity with a SharedElementTransition.

    Now in ActivityB's onCreate() method, you can just check for the boolean value passed to the Intent. If you passed false, then you can add a conditional statement and perform your UI updating there. I've given you a small snippet below to help you get started:

    private static final String isSharedElementTransitionEnabled = "IS_SHARED_ELEMENT_TRANSITION_ENABLED";    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
    
        // If you are postponing your SharedElementTransition, don't forget to call postponeEnterTransition() and override onPreDraw()
    
        if (!getIntent().getExtras().getBoolean(isSharedElementTransitionEnabled)) {
            //Do your UI updation here
        }
    }
    

    The good thing about doing it this way is that you can then have full control over how your content transitions and your shared element transitions will play out.

提交回复
热议问题