CollapsingToolbarLayout以编程方式扩展动画持续时间 [英] CollapsingToolbarLayout expand programmatically animation duration
问题描述
我正在Android的应用程序中使用CollapsingToolbarLayout。我的应用程序的最低要求API是9。
I'm using CollapsingToolbarLayout in my application in Android. My app's minimum requirement API is 9.
我需要在用户单击折叠的工具栏时展开折叠的工具栏,就像最新的Gmail日历的应用程序一样。因此,我设置了一个onClickListener,并在其中执行以下操作:
I need the collapsed toolbar to be expanded when the user clicks in the collapsed one, just like in latest Gmail Calendar's app. So I set an onClickListener and inside it I do the following:
public void onClick(View v) {
if(toolbarExpanded) {
mAppBar.setExpanded(false, true);
} else {
mAppBar.setExpanded(true, true);
}
toolbarExpanded = !toolbarExpanded;
}
效果不错,但我的问题是正在运行的动画是
Which is working quite well but my problem is that the animation that it's running is slow, meaning a bad user experience.
无论如何,是否需要更改持续时间或为此定义自定义动画?
Is there anyway to change the duration or to define a custom animation for this?
提前谢谢您。
推荐答案
注意:此答案基于android设计库v25.0.0。
Note: this answer is based on android design library v25.0.0.
您可以调用带有反射的NestedScrollView的AppBarLayout.Behavior的私有方法animateOffsetTo。此方法的速度参数会影响动画的持续时间。
You can call the private method animateOffsetTo of the AppBarLayout.Behavior of your NestedScrollView with reflection. This method has a velocity parameter that has an impact on the animation duration.
private void expandAppBarLayoutWithVelocity(AppBarLayout.Behavior behavior, CoordinatorLayout coordinatorLayout, AppBarLayout appBarLayout, float velocity) {
try {
//With reflection, we can call the private method of Behavior that expands the AppBarLayout with specified velocity
Method animateOffsetTo = AppBarLayout.Behavior.getClass().getDeclaredMethod("animateOffsetTo", CoordinatorLayout.class, AppBarLayout.class, int.class, float.class);
animateOffsetTo.setAccessible(true);
animateOffsetTo.invoke(behavior, coordinatorLayout, appBarLayout, 0, velocity);
} catch (Exception e) {
e.printStackTrace();
//If the reflection fails, we fall back to the public method setExpanded that expands the AppBarLayout with a fixed velocity
Log.e(TAG, "Failed to get animateOffsetTo method from AppBarLayout.Behavior through reflection. Falling back to setExpanded.");
appBarLayout.setExpanded(true, true);
}
}
要获取该行为,您需要从
To get the Behavior, you need to fetch it from the LayoutParams of your AppBarLayout.
AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.app_bar);
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior behavior = params.getBehavior();
这篇关于CollapsingToolbarLayout以编程方式扩展动画持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!