add 와 replace 중요성의 차이점은 replace 가 기존의 조각을 제거하고 새로운 조각을 추가하는 것입니다. 즉, 다시 버튼을 누르면 대체 된 프래그먼트가 호출되고 onCreateView가 호출됩니다. add 는 기존의 조각을 유지하고 기존의 조각이 활성화 될 것이라는 의미의 새 조각을 추가하는 반면 '뒤로'단추를 누르면 onCreateView가 기존 조각 (새 조각 전에 있던 단편 조각이 추가됨). 프래그먼트의 라이프 사이클 이벤트 onPause와 관련하여, onResume, onCreateView 및 기타 라이프 사이클 이벤트는 replace 될 경우 호출되지만 add 경우에는 호출되지 않습니다.
add() 와 replace() 기본적인 차이점은 다음과 같이 설명 할 수 있습니다.
add() 는 일부 루트 요소에 단편을 단순히 추가하는 데 사용됩니다.
replace() 비슷하게 동작하지만 이전에는 이전 조각을 제거한 후 다음 조각을 추가합니다.
addToBackStack() 을 add() 또는 replace() 와 함께 사용하면 정확한 차이를 확인할 수 있습니다.
add() ... onCreateView가 호출되지 않았을 때 back button을 누르면, replace() 경우에는 back 버튼을 누르면 ... oncreateView가 매번 호출됩니다.
Note that the shared element transitions require Android 5.0 (API level 21) and above and will be ignored for any lower API versions. Be sure to check the version at runtime before using API 21 specific features.
1. Enable Window Content Transitions
Enable Window Content Transitions in your styles.xml file:
<!-- Base application theme. -->
<stylename="AppTheme"parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<itemname="android:windowContentTransitions">true</item>
...
</style>
2. Assign a Common Transition Name
Assign a common transition name to the shared elements in both layouts. Use theandroid:transitionName attribute.
Note that it doesn't matter if the android:id is different or where in the layout hierarchy the source and target views exist.
3. Start Activity
Start the target activity by specifying a bundle of those shared elements and views from the source.
Intent intent =newIntent(this, DetailsActivity.class);
// Pass data object in the bundle and populate details activity.
intent.putExtra(DetailsActivity.EXTRA_CONTACT, contact);
ActivityOptionsCompat options =ActivityOptionsCompat.
makeSceneTransitionAnimation(this, (View)ivProfile, "profile");
startActivity(intent, options.toBundle());
Thats it! Specifying the source view along with the transition name ensures that even if you have multiple views with the same transition name in the source hierarchy, it will essentially be able to pick the right view to start the animation from.
To reverse the scene transition animation when you finish the second activity, call theActivity.supportFinishAfterTransition() method instead of Activity.finish(). Also, you will need to override the behavior of the home button in the ToolBar/ ActionBar for such cases:
@Overridepublicboolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home buttoncaseandroid.R.id.home:
supportFinishAfterTransition();
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
4. Multiple Shared Elements
Sometimes, you might want to animate multiple elements from the source view hierarchy. This can be achieved by using distinct transition names in the source and target layout xml files.
Note: By default android.util.Pair will be imported but we want to select theandroid.support.v4.util.Pair class instead.
Be careful to not overdo transitions between shared elements. While it can make sense to have one cohesive unit animate from one screen to another (which may or may not contain multiple shared elements), having too many shared elements will result in a distracting animation which makes the experience more jarring.
5. Customizing Shared Elements Transition
In Android L, shared elements transition defaults to a combination of ChangeBounds,ChangeTransform, ChangeImageTransform, and ChangeClipBounds. This works well for most typical cases. However, you may customize this behavior or even define your own custom transition.
<!-- Base application theme. -->
<stylename="AppTheme"parent="Theme.AppCompat.Light.DarkActionBar">
<!-- enable window content transitions -->
<itemname="android:windowContentTransitions">true</item>
<!-- specify enter and exit transitions --><!-- options are: explode, slide, fade -->
<itemname="android:windowEnterTransition">@transition/change_image_transform</item>
<itemname="android:windowExitTransition">@transition/change_image_transform</item>
<!-- specify shared element transitions -->
<itemname="android:windowSharedElementEnterTransition">
@transition/change_image_transform</item>
<itemname="android:windowSharedElementExitTransition">
@transition/change_image_transform</item>
</style>
The change_image_transform transition in this example is defined as follows:
To enable window content transitions at runtime instead, call the Window.requestFeature()method:
// inside your activity (if you did not enable transitions in your theme)
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
// set an enter transition
getWindow().setEnterTransition(newExplode());
// set an exit transition
getWindow().setExitTransition(newExplode());
Leveraging shared element transitions works with fragments too in a similar way as was shown above for activities.
Note that the shared element transitions require Android 5.0 (API level 21) and above and will be ignored for any lower API versions. Be sure to check the version at runtime before using API 21 specific features.
Assign a Common Transition Name
Within two fragments let's assign a common transition name to the shared elements in both layouts. Use the android:transitionName attribute and put the view inside bothFirstFragment and SecondFragment:
Now within the activity, we can trigger the transition as part of any FragmentTransaction:
// Get access to or create instances to each fragmentFirstFragment fragmentOne =...;
SecondFragment fragmentTwo =...;
// Check that the device is running lollipopif (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
// Inflate transitions to applyTransition changeTransform =TransitionInflater.from(this).
inflateTransition(R.transition.change_image_transform);
Transition explodeTransform =TransitionInflater.from(this).
inflateTransition(android.R.transition.explode);
// Setup exit transition on first fragment
fragmentOne.setSharedElementReturnTransition(changeTransform);
fragmentOne.setExitTransition(explodeTransform);
// Setup enter transition on second fragment
fragmentTwo.setSharedElementEnterTransition(changeTransform);
fragmentTwo.setEnterTransition(explodeTransform);
// Find the shared element (in Fragment A)ImageView ivProfile = (ImageView) findViewById(R.id.ivProfile);
// Add second fragment by replacing first FragmentTransaction ft = getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentTwo)
.addToBackStack("transaction")
.addSharedElement(ivProfile, "profile");
// Apply the transaction
ft.commit();
}
else {
// Code to run on older devices
}
Note that we need use methods on the exiting fragment such assetSharedElementReturnTransition and setExitTransition. On the entering fragment, we call setSharedElementEnterTransition and setEnterTransition. Finally we need to find the instance of the shared element and then call addSharedElement(view, transitionName) as part of building the FragmentTransaction. Additional external resources for fragment-to-fragment shared element transitions include:
기존 Android SDK 버전에서는 설치 시 해당 앱에 설정 된 permission을 물어보고 동의를 해야만 설치가 가능했다. 하지만, Android 6.0(SDK 23)이상의 버전에서는 설치 시에 묻는게 아니라 해당 기능이 permission을 필요로 할 때, permission을 활성화 해줘야 사용가능하다. 따라서 기존 6.0미만의 버전에서 개발했던 어플리케이션은 6.0이상의 폰에서는 정상적으로 작동하지 않을 수 있다.