2015-12-30 62 views
1

我在Android的应用程序中使用了CollapsingToolbarLayout。我的应用程序的最低要求API为9.CollapsingToolbarLayout以编程方式展开动画持续时间

我需要在用户点击折叠的工具栏时展开折叠的工具栏,就像在最新的Gmail日历应用程序中一样。所以我设置onClickListener和里面我做了以下内容:

public void onClick(View v) { 
    if(toolbarExpanded) { 
     mAppBar.setExpanded(false, true); 
    } else { 
     mAppBar.setExpanded(true, true); 
    } 
    toolbarExpanded = !toolbarExpanded; 
} 

这是合作得非常好,但我的问题是,它的运行动画是缓慢的,这意味着一个不好的用户体验。

无论如何改变持续时间或为此定义一个自定义动画?

预先感谢您。

+1

解决办法是回滚到'编译“com.android.support:design:23.1.0关闭“我害怕。”这种行为最近由google引入,在这里阅读更多:http://stackoverflow.com/questions/33892376/appbarlayout-setexpandedboolean-true-weird-animation-in-support-library-23-1 –

回答

3

注意:此答案是基于android设计库v25.0.0。

您可以用反射调用NestedScrollView的AppBarLayout.Behavior的私有方法animateOffsetTo。此方法具有影响动画持续时间的速度参数。

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); 
    } 
} 

要获得行为,您需要从AppBarLayout的LayoutParams中获取它。

AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.app_bar); 
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams(); 
AppBarLayout.Behavior behavior = params.getBehavior(); 
+0

完美的作品,如何可以我以编程方式崩溃#Raphael Royer-Rivard –

1

为了动画使用扩大

AppBarLayout.setExpanded(true,true); 

为了动画使用

AppBarLayout.setExpanded(false,true);