我正在使用Android Studio 3.2 Canary 14和The Navigation Architecture Component。使用此功能,您可以像使用Intent一样定义过渡动画。
但是动画被设置为导航图中动作的属性,如下所示:
<fragment
android:id="@+id/startScreenFragment"
android:name="com.example.startScreen.StartScreenFragment"
android:label="fragment_start_screen"
tools:layout="@layout/fragment_start_screen" >
<action
android:id="@+id/action_startScreenFragment_to_findAddressFragment"
app:destination="@id/findAddressFragment"
app:enterAnim="@animator/slide_in_right"
app:exitAnim="@animator/slide_out_left"
app:popEnterAnim="@animator/slide_in_left"
app:popExitAnim="@animator/slide_out_right"/>
</fragment>
为图表中的所有操作定义都很繁琐!
有没有办法在动作中将一组动画定义为默认值?
我没有运气使用款式。
答案 0 :(得分:7)
R.anim具有定义的默认动画(最终):
List<MenuPrice> menuPrices = findAll(restaurant);
menuPrices
.parallelStream()
.collect(Collectors.groupingBy(MenuPrice::getUpdateDate()));
nav_default_enter_anim
nav_default_exit_anim
nav_default_pop_enter_anim
要更改此行为,您必须使用自定义NavOptions,
因为这是将这些动画分配给NavAction的地方。
一个人可以用NavOptions.Builder分配它们:
nav_default_pop_exit_anim
最有可能需要创建一个protected NavOptions getNavOptions() {
NavOptions navOptions = NavOptions.Builder()
.setEnterAnim(R.anim.default_enter_anim)
.setExitAnim(R.anim.default_exit_anim)
.setPopEnterAnim(R.anim.default_pop_enter_anim)
.setPopExitAnim(R.anim.default_pop_exit_anim)
.build();
return navOptions;
}
,它扩展了类androidx.navigation.fragment(那里的文档似乎尚未完成)。
或者...查看该软件包的DefaultNavFragment
时;这些动画 可以设置样式:
attrs.xml
这意味着,可以定义相应的样式-并将其定义为主题的一部分...
一个人可以在<resources>
<declare-styleable name="NavAction">
<attr name="enterAnim" format="reference"/>
<attr name="exitAnim" format="reference"/>
<attr name="popEnterAnim" format="reference"/>
<attr name="popExitAnim" format="reference"/>
...
</declare-styleable>
</resources>
中定义它们:
styles.xml
答案 1 :(得分:5)
我找到了需要扩展 NavHostFragment
的解决方案。它类似于 Link182,但较少涉及代码。大多数情况下,它需要从标准更改所有 xml defaultNavHost 片段名称:
<fragment
app:defaultNavHost="true"
...
android:name="androidx.navigation.fragment.NavHostFragment"
到:
<fragment
app:defaultNavHost="true"
...
android:name="your.app.package.fragments.NavHostFragmentWithDefaultAnimations"
NavHostFragmentWithDefaultAnimations
的代码:
package your.app.package.fragments
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.navigation.*
import androidx.navigation.fragment.FragmentNavigator
import androidx.navigation.fragment.NavHostFragment
import your.app.package.R
// Those are navigation-ui (androidx.navigation.ui) defaults
// used in NavigationUI for NavigationView and BottomNavigationView.
// Set yours here
private val defaultNavOptions = navOptions {
anim {
enter = R.animator.nav_default_enter_anim
exit = R.animator.nav_default_exit_anim
popEnter = R.animator.nav_default_pop_enter_anim
popExit = R.animator.nav_default_pop_exit_anim
}
}
private val emptyNavOptions = navOptions {}
class NavHostFragmentWithDefaultAnimations : NavHostFragment() {
override fun onCreateNavController(navController: NavController) {
super.onCreateNavController(navController)
navController.navigatorProvider.addNavigator(
// this replaces FragmentNavigator
FragmentNavigatorWithDefaultAnimations(requireContext(), childFragmentManager, id)
)
}
}
/**
* Needs to replace FragmentNavigator and replacing is done with name in annotation.
* Navigation method will use defaults for fragments transitions animations.
*/
@Navigator.Name("fragment")
class FragmentNavigatorWithDefaultAnimations(
context: Context,
manager: FragmentManager,
containerId: Int
) : FragmentNavigator(context, manager, containerId) {
override fun navigate(
destination: Destination,
args: Bundle?,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
): NavDestination? {
// this will try to fill in empty animations with defaults when no shared element transitions are set
// https://developer.android.com/guide/navigation/navigation-animate-transitions#shared-element
val shouldUseTransitionsInstead = navigatorExtras != null
val navOptions = if (shouldUseTransitionsInstead) navOptions
else navOptions.fillEmptyAnimationsWithDefaults()
return super.navigate(destination, args, navOptions, navigatorExtras)
}
private fun NavOptions?.fillEmptyAnimationsWithDefaults(): NavOptions =
this?.copyNavOptionsWithDefaultAnimations() ?: defaultNavOptions
private fun NavOptions.copyNavOptionsWithDefaultAnimations(): NavOptions =
let { originalNavOptions ->
navOptions {
launchSingleTop = originalNavOptions.shouldLaunchSingleTop()
popUpTo(originalNavOptions.popUpTo) {
inclusive = originalNavOptions.isPopUpToInclusive
}
anim {
enter =
if (originalNavOptions.enterAnim == emptyNavOptions.enterAnim) defaultNavOptions.enterAnim
else originalNavOptions.enterAnim
exit =
if (originalNavOptions.exitAnim == emptyNavOptions.exitAnim) defaultNavOptions.exitAnim
else originalNavOptions.exitAnim
popEnter =
if (originalNavOptions.popEnterAnim == emptyNavOptions.popEnterAnim) defaultNavOptions.popEnterAnim
else originalNavOptions.popEnterAnim
popExit =
if (originalNavOptions.popExitAnim == emptyNavOptions.popExitAnim) defaultNavOptions.popExitAnim
else originalNavOptions.popExitAnim
}
}
}
}
您可以通过传递 navOptions 在导航图 xml 或代码中更改动画。 要禁用默认动画,请传递动画值为 0 的 navOptions 或传递 navigatorExtras(设置共享过渡)。
测试版本:
implementation "androidx.navigation:navigation-fragment-ktx:2.3.1"
implementation "androidx.navigation:navigation-ui-ktx:2.3.1"
答案 2 :(得分:0)
如前所述,R.anim具有定义的默认动画:
nav_default_enter_anim
nav_default_exit_anim
nav_default_pop_enter_anim
nav_default_pop_exit_anim
但是您可以轻松地覆盖它们。
只需在应用模块中创建自己的四个具有相同名称的动画资源(为清楚起见,其中一个的ID为your.package.name.R.anim.nav_default_enter_anim
),然后编写所需的动画即可。
答案 3 :(得分:0)
可以使用自定义androidx.navigation.fragment.Navigator
。
我将演示如何覆盖fragment
导航。这是我们的自定义导航器。注意setAnimations()
方法
@Navigator.Name("fragment")
class MyAwesomeFragmentNavigator(
private val context: Context,
private val manager: FragmentManager, // Should pass childFragmentManager.
private val containerId: Int
): FragmentNavigator(context, manager, containerId) {
private val backStack by lazy {
this::class.java.superclass!!.getDeclaredField("mBackStack").let {
it.isAccessible = true
it.get(this) as ArrayDeque<Integer>
}
}
override fun navigate(destination: Destination, args: Bundle?, navOptions: NavOptions?, navigatorExtras: Navigator.Extras?): NavDestination? {
if (manager.isStateSaved) {
logi("Ignoring navigate() call: FragmentManager has already"
+ " saved its state")
return null
}
var className = destination.className
if (className[0] == '.') {
className = context.packageName + className
}
val frag = instantiateFragment(context, manager,
className, args)
frag.arguments = args
val ft = manager.beginTransaction()
navOptions?.let { setAnimations(it, ft) }
ft.replace(containerId, frag)
ft.setPrimaryNavigationFragment(frag)
@IdRes val destId = destination.id
val initialNavigation = backStack.isEmpty()
// TODO Build first class singleTop behavior for fragments
val isSingleTopReplacement = (navOptions != null && !initialNavigation
&& navOptions.shouldLaunchSingleTop()
&& backStack.peekLast()?.toInt() == destId)
val isAdded: Boolean
isAdded = if (initialNavigation) {
true
} else if (isSingleTopReplacement) { // Single Top means we only want one
instance on the back stack
if (backStack.size > 1) { // If the Fragment to be replaced is on the FragmentManager's
// back stack, a simple replace() isn't enough so we
// remove it from the back stack and put our replacement
// on the back stack in its place
manager.popBackStack(
generateBackStackName(backStack.size, backStack.peekLast()!!.toInt()),
FragmentManager.POP_BACK_STACK_INCLUSIVE)
ft.addToBackStack(generateBackStackName(backStack.size, destId))
}
false
} else {
ft.addToBackStack(generateBackStackName(backStack.size + 1, destId))
true
}
if (navigatorExtras is Extras) {
for ((key, value) in navigatorExtras.sharedElements) {
ft.addSharedElement(key!!, value!!)
}
}
ft.setReorderingAllowed(true)
ft.commit()
// The commit succeeded, update our view of the world
return if (isAdded) {
backStack.add(Integer(destId))
destination
} else {
null
}
}
private fun setAnimations(navOptions: NavOptions, transaction: FragmentTransaction) {
transaction.setCustomAnimations(
navOptions.enterAnim.takeIf { it != -1 } ?: android.R.anim.fade_in,
navOptions.exitAnim.takeIf { it != -1 } ?: android.R.anim.fade_out,
navOptions.popEnterAnim.takeIf { it != -1 } ?: android.R.anim.fade_in,
navOptions.popExitAnim.takeIf { it != -1 } ?: android.R.anim.fade_out
)
}
private fun generateBackStackName(backStackIndex: Int, destId: Int): String? {
return "$backStackIndex-$destId"
}
}
下一步,我们必须将导航器添加到NavController
。这是一个设置方法的示例:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainer)!!
with (findNavController(R.id.fragmentContainer)) {
navigatorProvider += MyAwesomeFragmentNavigator(this@BaseContainerActivity, navHostFragment.childFragmentManager, R.id.fragmentContainer)
setGraph(navGraphId)
}
}
在xml中没什么特别的:)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/fragmentContainer"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true" />
</LinearLayout>
现在图中的每个片段都将具有alpha过渡