Activity transition in Android

2019-01-01 06:37发布

How can I define the transition between two activities for Android 1.5 and later? I would like an activity to fade in.

14条回答
与君花间醉酒
2楼-- · 2019-01-01 07:04

Use ActivityCompat.startActivity() works API > 21.

    ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionImage, EXTRA_IMAGE);
    ActivityCompat.startActivity(activity, intent, options.toBundle());
查看更多
人气声优
3楼-- · 2019-01-01 07:05

Some versions of Android support custom Activity transitions and some don't (older devices). If you want to use custom transitions it's good practice to check whether the Activity has the overridePendingTransition() method, as on older versions it does not.

To know whether the method exists or not, reflection API can be used. Here is the simple code which will check and return the method if it exists:

Method mOverridePendingTransition;

try {
        mOverridePendingTransition = Activity.class.getMethod(
                "overridePendingTransition", new Class[] { Integer.TYPE, Integer.TYPE } );
        /* success */
    } catch (NoSuchMethodException nsme) {
        /* failure, this version of Android doesn't have this method */
    } 

And then, we can apply our own transition, i.e. use this method if it exists:

if (UIConstants.mOverridePendingTransition != null) {
               try {
                   UIConstants.mOverridePendingTransition.invoke(MainActivity.this, R.anim.activity_fade_in, R.anim.activity_fade_out);
               } catch (InvocationTargetException e) {
                   e.printStackTrace();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
            }

Here, as an example, simple fade-in and fade-out animations were used for transition demonstration..

查看更多
登录 后发表回答