Android Design风格组件之FloatingActionButton

概览

浮动操作按钮 (简称 FAB) 是: “一个特殊的promoted操作案例。因为一个浮动在UI之上的圆形图标而显得格外突出,同时它还具有特殊的手势行为”


比如,如果我们在使用email app,在列出收件箱邮件列表的时候,promoted操作可能就是新建一封邮件。

1437174714327988.png  blob.png

浮动操作按钮代表一个屏幕之内最基本的额操作。关于FAB按钮的更多信息和使用案例请参考谷歌的官方设计规范

用法

谷歌在2015年的 I/O大会上公布了可以创建浮动操作按钮的支持库,但是在这之前,则须使用诸如makovkastar/FloatingActionButton 和 futuresimple/android-floating-action-button 这样的第三方库。

Design Support Library

首先确保你按照Design Support Library中的指导来配置。

现在你可以把android.support.design.widget.FloatingActionButton添加到布局中了。其中src属性指的是浮动按钮所要的图标。

 
 
  1.      <android.support.design.widget.FloatingActionButton
  2.         android:src="@drawable/ic_done"
  3.         app:fabSize="normal"
  4.         android:layout_width="wrap_content"
  5.         android:layout_height="wrap_content" />

另外,如果在布局的最顶部声明了xmlns:app="http://schemas.android.com/apk/res-auto命名空间,你还可以定义一个fabSize属性,该属性决定按钮是正常大小还是小号。


放置浮动操作按钮需要使用CoordinatorLayout。CoordinatorLayout帮助我们协调它所包含的子view之间的交互,这一点在我们后面讲如何根据滚动的变化让按钮动画隐藏与显示的时候有用。但是目前我们能从CoordinatorLayout得到的好处是它可以让一个元素浮动在另一个元素之上。我们只需让FloatingActionButton和ListView被包含在CoordinatorLayout中,然后使用layout_anchor 与 layout_anchorGravity 属性就可以了。

 
 
  1. <android.support.design.widget.CoordinatorLayout
  2.     android:id="@+id/main_content"
  3.     xmlns:android="http://schemas.android.com/apk/res/android"
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent">
  7.  
  8.           <ListView
  9.               android:id="@+id/lvToDoList"
  10.               android:layout_width="match_parent"
  11.               android:layout_height="match_parent"></ListView>
  12.  
  13.           <android.support.design.widget.FloatingActionButton
  14.               android:layout_width="wrap_content"
  15.               android:layout_height="wrap_content"
  16.               android:layout_gravity="bottom|right"
  17.               android:layout_margin="16dp"
  18.               android:src="@drawable/ic_done"
  19.               app:layout_anchor="@id/lvToDoList"
  20.               app:layout_anchorGravity="bottom|right|end" />
  21. </android.support.design.widget.CoordinatorLayout>

按钮应该处于屏幕的右下角。建议在手机上下方的margin设置为16dp而平板上设置为24dp。上面的例子中,使用的是16dp。

而根据谷歌的设计规范,drawable的尺寸应该是24dp。

1437174898107751.png

浮动操作按钮的动画

当用户往下滚动一个页面,浮动操作按钮应该消失,一旦向上滚动,则重现。

blob.png

要让这个过程有动画效果,你需要利用好CoordinatorLayoutCoordinatorLayout帮助协调定义在里面的view之间的动画。

用RecyclerView替换ListViews

目前,你需要用RecyclerView来替换ListViews。就如这节所描述的,RecyclerView是ListViews的继承者。根据谷歌的这篇文章所讲的,不支持CoordinatorLayout和ListView一起使用。你可以查看这篇指南,它帮助你过渡到RecyclerView。

 
 
  1. <android.support.v7.widget.RecyclerView
  2.          android:id="@+id/lvToDoList"
  3.          android:layout_width="match_parent"
  4.          android:layout_height="match_parent"
  5. </android.support.v7.widget.RecyclerView>

同时你还必须把RecyclerView升级到v22版本,之前的v21不支持与CoordinatorLayout一起工作,确保你的build.gradle 文件是这样的:

 
 
  1.   compile 'com.android.support:recyclerview-v7:22.2.0'

使用CoordinatorLayout

接下来,你需要现为浮动操作按钮实现CoordinatorLayout Behavior。这个类用于定义按钮该如何响应包含在同一CoordinatorLayout之内的其它view。

创建一个继承自 FloatingActionButton.Behavior 名叫ScrollAwareFABBehavior.java的类。目前浮动操作按钮默认的behavior是为Snackbar让出空间,就如这个视频中的效果。

我们想继承这个behavior,暗示我们希望处理垂直方向上的滚动事件:

 
 
  1. public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
  2.  
  3.     @Override
  4.     public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
  5.             FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
  6.         return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || 
  7.             super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
  8.             nestedScrollAxes);
  9.     }}

因为这个类要处理滚动,另外一个onNestedScroll() 方法将被调用,我们可以检查Y的位置,并决定按钮是否动画进入或退出:

 
 
  1. public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
  2.     // ...
  3.  
  4.     @Override
  5.     public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
  6.             View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
  7.         super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
  8.                 dyUnconsumed);
  9.  
  10.         if (dyConsumed > 0 && !this.mIsAnimatingOut && child.getVisibility() == View.VISIBLE) {
  11.             animateOut(child);
  12.         } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
  13.             animateIn(child);
  14.         }
  15.     }
  16.  
  17.     // ...}

因为FloatingActionButton.Behavior的基类已经有了animateIn() 和 animateOut()方法,同时它也设置了一个私有变量mIsAnimatingOut,这些方法和变量都是私有的,所以现在我们需要重新实现这些动画方法。

 
 
  1. public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
  2.  
  3.     private static final android.view.animation.Interpolator INTERPOLATOR = 
  4.         new FastOutSlowInInterpolator();
  5.     private boolean mIsAnimatingOut = false;
  6.  
  7.     // Same animation that FloatingActionButton.Behavior uses to 
  8.     // hide the FAB when the AppBarLayout exits
  9.     private void animateOut(final FloatingActionButton button) {
  10.         if (Build.VERSION.SDK_INT >= 14) {
  11.            ViewCompat.animate(button).scaleX(0.0F).scaleY(0.0F).alpha(0.0F)
  12.                     .setInterpolator(INTERPOLATOR).withLayer()
  13.                     .setListener(new ViewPropertyAnimatorListener() {
  14.                         public void onAnimationStart(View view) {
  15.                             ScrollAwareFABBehavior.this.mIsAnimatingOut = true;
  16.                         }
  17.  
  18.                         public void onAnimationCancel(View view) {
  19.                             ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
  20.                         }
  21.  
  22.                         public void onAnimationEnd(View view) {
  23.                             ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
  24.                             view.setVisibility(View.GONE);
  25.                         }
  26.                     }).start();
  27.         } else {
  28.             Animation anim = AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_out);
  29.             anim.setInterpolator(INTERPOLATOR);
  30.             anim.setDuration(200L);
  31.             anim.setAnimationListener(new Animation.AnimationListener() {
  32.                 public void onAnimationStart(Animation animation) {
  33.                     ScrollAwareFABBehavior.this.mIsAnimatingOut = true;
  34.                 }
  35.  
  36.                 public void onAnimationEnd(Animation animation) {
  37.                     ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
  38.                     button.setVisibility(View.GONE);
  39.                 }
  40.  
  41.                 @Override
  42.                 public void onAnimationRepeat(final Animation animation) {
  43.                 }
  44.             });
  45.             button.startAnimation(anim);
  46.         }
  47.     }
  48.  
  49.     // Same animation that FloatingActionButton.Behavior 
  50.     // uses to show the FAB when the AppBarLayout enters
  51.     private void animateIn(FloatingActionButton button) {
  52.         button.setVisibility(View.VISIBLE);
  53.         if (Build.VERSION.SDK_INT >= 14) {
  54.             ViewCompat.animate(button).scaleX(1.0F).scaleY(1.0F).alpha(1.0F)
  55.                     .setInterpolator(INTERPOLATOR).withLayer().setListener(null)
  56.                     .start();
  57.         } else {
  58.             Animation anim = AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_in);
  59.             anim.setDuration(200L);
  60.             anim.setInterpolator(INTERPOLATOR);
  61.             button.startAnimation(anim);
  62.         }
  63.     }
  64. }

最后一步就是把这个CoordinatorLayout Behavior与浮动操作按钮联系起来。我们可以在xml的自定义属性pp:layout_behavior中定义它:

 
 
  1. <android.support.design.widget.FloatingActionButton    
  2.     app:layout_behavior="com.codepath.floatingactionbuttontest.ScrollAwareFABBehavior" />

因为我们是在xml中静态的定义这个behavior,为了让 layout inflation顺利进行,我们必须实现一个构造函数。

 
 
  1. public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
  2.     // ...
  3.  
  4.     public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
  5.         super();
  6.     }
  7.  
  8.    // ...}

如果你忘记实现这个方法,你会看到“Could not inflate Behavior subclass”错误信息。完整的用法可以看看这个example code 。

注:通常,当我们实现CoordinatorLayout behavior的时候,我们需要实现layoutDependsOn() 和 onDependentViewChanged(),它们用于跟踪CoordinatorLayout中其他view的变化。不过既然我们只需要监控滚动变化,我们就直接使用为浮动操作按钮定义的现成behavior,就如这篇博客讨论的,这个behavior现在被实现来跟踪Snackbar和AppBarLayout的变化。

注意这里有一个已知的bug :在和RecyclerView使用的时候,如果滚动过快,会触发NullPointerException,文档在这里。该问题会在这个库的下一版本被修复。

使用FloatingActionButton (第三方)

使用makovkastar/FloatingActionButton 库可以让浮动操作按钮的设置变的非常简单。可以参考library 文档 以及例子源码 。

First, add as a dependency to your app/build.gradle:

首先,在app/build.gradle:中添加一个依赖:

 
 
  1. dependencies {
  2.     compile 'com.melnykov:floatingactionbutton:1.2.0'
  3. }

接下来,在布局中添加com.melnykov.fab.FloatingActionButton 。记得在根布局中属性中添加xmlns:fab

 
 
  1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.              xmlns:fab="http://schemas.android.com/apk/res-auto"
  3.              android:layout_width="match_parent"
  4.              android:layout_height="match_parent">
  5.  
  6.     <ListView
  7.             android:id="@android:id/list"
  8.             android:layout_width="match_parent"
  9.             android:layout_height="match_parent" />
  10.  
  11.     <com.melnykov.fab.FloatingActionButton
  12.             android:id="@+id/fab"
  13.             android:layout_width="wrap_content"
  14.             android:layout_height="wrap_content"
  15.             android:layout_gravity="bottom|right"
  16.             android:layout_margin="16dp"
  17.             android:src="@drawable/ic_action_content_new"
  18.             fab:fab_type="normal"
  19.             fab:fab_shadow="true"
  20.             fab:fab_colorNormal="@color/primary"
  21.             fab:fab_colorPressed="@color/primary_pressed"
  22.             fab:fab_colorRipple="@color/ripple" />
  23. </FrameLayout>

依附到list

接下来,我们可以选择将FAB和一个ListView, ScrollView 或者 RecyclerView 关联起来,这样按钮就会随着list的向下滚动而隐藏,向上滚动而重现:

 
 
  1. ListView listView = (ListView) findViewById(android.R.id.list);
  2. FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
  3. fab.attachToListView(listView); // or attachToRecyclerView

我们可以使用fab.attachToRecyclerView(recyclerView)来依附到一个RecyclerView,或者使用fab.attachToScrollView(scrollView)来依附到一个ScrollView。

调整按钮类型

浮动操作按钮有两种大小:默认的,这应该是最常用的情况,以及mini的,这应该只用于衔接屏幕上的其他元素。

注:我认为下图这种使用实在是太鸡肋了。

1437175256115824.png

我可以把FAB的按钮类型调整为“正常”或者“mini”

 
 
  1. <com.melnykov.fab.FloatingActionButton
  2.     ...
  3.     fab:fab_type="mini" />
FAB的显示和隐藏

分别显示和隐藏按钮:

 
 
  1. // 带动画的显示和隐藏
  2. fab.show();
  3. fab.hide();
  4. // 不带动画的
  5. fab.show(false);
  6. fab.hide(false);

监听滚动事件

我们可以监听所关联的list的滚动事件,以管理FAB的状态:

 
 
  1. FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab);
  2. fab.attachToListView(list, new ScrollDirectionListener() {
  3.     @Override
  4.     public void onScrollDown() {
  5.         Log.d("ListViewFragment", "onScrollDown()");
  6.     }
  7.  
  8.     @Override
  9.     public void onScrollUp() {
  10.         Log.d("ListViewFragment", "onScrollUp()");
  11.     }
  12. }, new AbsListView.OnScrollListener() {
  13.     @Override
  14.     public void onScrollStateChanged(AbsListView view, int scrollState) {
  15.         Log.d("ListViewFragment", "onScrollStateChanged()");
  16.     }
  17.  
  18.     @Override
  19.     public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 
  20.         int totalItemCount) {
  21.         Log.d("ListViewFragment", "onScroll()");
  22.     }
  23. });

手动实现

除了使用库之外,我们还可以自己开发动操作按钮。关于手动实现浮动操作按钮,可以查看big nerd ranch guide 以及 survivingwithandroid walkthrough

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值