【Android - MD】之FloatingActionButton的使用

FloatingActionButton(FAB) 是 Android 5.0 新特性——Material Design 中的一个控件,是一种悬浮的按钮。

FloatingActionButton 是 ImageView 的子类,因此它具备ImageView的全部属性。

FloatingActionButton 结合 CoordinatorLayout 使用,即可实现悬浮在任意控件的任意位置。

使用 FloatingActionButton 的难点主要是布局,其在JAVA代码中的用法和普通的 ImageView 基本相同。

跟所有MD控件一样,要使用FAB,需要在gradle文件中先注册依赖:

compile ‘com.android.support:design:25.0.0‘

1、FAB 基本属性:

        android:src:FAB中显示的图标,最好是24dp的
        app:backgroundTint:正常的背景颜色
        app:rippleColor:按下时的背景颜色
        app:elevation:正常的阴影大小
        app:pressedTranslationZ:按下时的阴影大小
        app:layout_anchor:设置FAB的锚点,即以哪个控件为参照设置位置
        app:layout_anchorGravity:FAB相对于锚点的位置
        app:fabSize:FAB的大小,normal或mini(对应56dp和40dp)
        注意:要想让FAB显示点击后的颜色和阴影变化效果,必须设置onClick事件

实例布局代码:

<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20.0dip"
        android:onClick="click"
        android:src="@mipmap/ic_launcher"
        app:backgroundTint="#30469b"
        app:borderWidth="0.0dip"
        app:elevation="5.0dip"
        app:fabSize="normal"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="right|bottom"
        app:pressedTranslationZ="10.0dip"
        app:rippleColor="#a6a6a6" />

</android.support.design.widget.CoordinatorLayout>

运行结果图:

2、交互事件:

FloatingActionButton 的用法和ImageView基本相同,要想设置FloatingActionButton的点击事件,直接调用setOnClickListener()方法即可。

值得一提的是,当FloatingActionButton与Snackbar一起使用的时候,有时候会发生“Snackbar将FloatingActionButton覆盖”的问题,即FloatingActionButton不会因为Snackbar的弹出而上移,这是因为Snackbar的make()方法第一个参数没有与FloatingActionButton绑定,只要Snackbar的make()方法第一个参数是FloatingActionButton对象,就不会出现上述问题,实例代码如下:

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 第一个参数设置为FAB就可以使FAB跟随Snackbar移动
                Snackbar.make(v, "去下一页?", Snackbar.LENGTH_LONG).setAction("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, NextActivity.class));
                    }
                }).show();
            }
        });

运行结果如下图:

       

3、FAB 滑动隐藏/显示:

很多应用中都有这种界面:界面中有一个FAB和一个RecyclerView,当RecyclerView向下滑动时,FAB消失;当RecyclerView向上滑动时,FAB又显示出来。这是FAB与RecyclerView、CoordinatorLayout结合使用的结果。通过设置FAB在CoordinatorLayout中的Behavior来实现这种效果。下面贴代码:

布局代码:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_next"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/next_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/next_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20.0dip"
        android:onClick="click"
        android:src="@mipmap/ic_launcher"
        app:backgroundTint="@color/colorPrimaryDark"
        app:elevation="5.0dip"
        app:fabSize="normal"
        app:layout_anchor="@id/next_rv"
        app:layout_anchorGravity="bottom|right"
        app:layout_behavior="com.example.testfloatingactionbutton.ScrollAwareFABBehavior"
        app:pressedTranslationZ="10.0dip"
        app:rippleColor="@color/colorPrimary" />

</android.support.design.widget.CoordinatorLayout>

ScrollAwareFABBehavior类中的代码:

public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
    // 动画插值器,可以控制动画的变化率
    private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();

    // 是否正在执行隐藏的动画
    private boolean mIsAnimatingOut = false;

    public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
        super();
    }

    @Override
    public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
                                       final View directTargetChild, final View target, final int nestedScrollAxes) {
        // 如果是上下滑动的,则返回true
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
                || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
    }

    @Override
    public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
                               final View target, final int dxConsumed, final int dyConsumed,
                               final int dxUnconsumed, final int dyUnconsumed) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
        if (dyConsumed > 0 && !this.mIsAnimatingOut && child.getVisibility() == View.VISIBLE) {
            // 用户向下滑动时判断是否正在执行隐藏动画,如果不是,而且FAB当前是可见的,则执行隐藏动画隐藏FAB
            animateOut(child);
        } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
            // 用户向上滑动时判断FAB是否可见,如果不可见则执行显示动画显示FAB
            animateIn(child);
        }
    }

    // Same animation that FloatingActionButton.Behavior uses to hide the FAB when the AppBarLayout exits
    // 执行隐藏动画隐藏FAB
    private void animateOut(final FloatingActionButton button) {
        if (Build.VERSION.SDK_INT >= 14) {
            ViewCompat.animate(button).scaleX(0.0F).scaleY(0.0F).alpha(0.0F).setInterpolator(INTERPOLATOR).withLayer()
                    .setListener(new ViewPropertyAnimatorListener() {
                        public void onAnimationStart(View view) {
                            ScrollAwareFABBehavior.this.mIsAnimatingOut = true;
                        }

                        public void onAnimationCancel(View view) {
                            ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
                        }

                        public void onAnimationEnd(View view) {
                            ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
                            view.setVisibility(View.GONE);
                        }
                    }).start();
        } else {
            Animation anim = AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_out);
            anim.setInterpolator(INTERPOLATOR);
            anim.setDuration(200L);
            anim.setAnimationListener(new Animation.AnimationListener() {
                public void onAnimationStart(Animation animation) {
                    ScrollAwareFABBehavior.this.mIsAnimatingOut = true;
                }

                public void onAnimationEnd(Animation animation) {
                    ScrollAwareFABBehavior.this.mIsAnimatingOut = false;
                    button.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(final Animation animation) {
                }
            });
            button.startAnimation(anim);
        }
    }

    // Same animation that FloatingActionButton.Behavior uses to show the FAB when the AppBarLayout enters
    // 执行显示动画显示FAB
    private void animateIn(FloatingActionButton button) {
        button.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= 14) {
            ViewCompat.animate(button).scaleX(1.0F).scaleY(1.0F).alpha(1.0F)
                    .setInterpolator(INTERPOLATOR).withLayer().setListener(null)
                    .start();
        } else {
            Animation anim = AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_in);
            anim.setDuration(200L);
            anim.setInterpolator(INTERPOLATOR);
            button.startAnimation(anim);
        }
    }
}

FAB显示的动画fab_in:

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:zAdjustment="top">
    <scale
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%p"
        android:pivotY="50%p"
        android:toXScale=".5"
        android:toYScale=".5" />
    <alpha
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromAlpha="1.0"
        android:toAlpha="0" />
</set>

FAB隐藏的动画fab_out:

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/decelerate_interpolator">
        <scale
            android:duration="@android:integer/config_mediumAnimTime"
            android:fromXScale="2.0"
            android:fromYScale="2.0"
            android:pivotX="50%p"
            android:pivotY="50%p"
            android:toXScale="1.0"
            android:toYScale="1.0" />
    </set>
</set>

运行效果如下图:

以上就是对FloatingActionButton用法的简单介绍,下面贴出码云上的代码,供大家参考。

DEMO地址

时间: 2024-08-01 06:25:01

【Android - MD】之FloatingActionButton的使用的相关文章

【Android - MD】之TextInputLayout的使用

TextInputLayout是Android 5.0新特性--Material Design中的一个布局控件,主要用来嵌套EditText,实现数据输入时的一些效果,如: 当输入框获取焦点时,输入提示语会动画移动到输入框上方: 当输入框失去焦点时,如果输入框中没有文本,则提示语动画移动回到输入框中: 当输入不合规范时,会在输入框下方显示错误提示语: 当输入的是密码时,可以选择是否显示"显示密码"的按钮以及按钮的图案: 可以显示输入框中当前文本的长度和要求的长度,等. 需要特别注意的是

【Android - MD】之TabLayout的使用

TabLayout是Android 5.0新特性--Material Design中的一个控件,是一个标签页的导航条,常结合ViewPager完成页面导航. 和其他MD控件一样,使用TabLayout之前需要在gradle文件中声明依赖: compile 'com.android.support:design:25.0.0' 1.TabLayout的属性: app:tabIndicatorColor:TabLayout下面提示条的颜色 app:tabIndicatorHeight:TabLayo

【Android - MD】之NavigationView的使用

NavigationView是Android 5.0新特性--Material Design中的一个布局控件,可以结合DrawerLayout使用,让侧滑菜单变得更加美观(可以添加头部布局). NavigationView需要嵌套在DrawerLayout内部,其相对于单独使用DrawerLayout的优点在于可以额外添加一个HeaderView头部布局.另外,NavigationView中的其他选项都是用menu的形式来编写的,menu中的分支也可以在NavigationView中形成分栏效果

【Android - MD】之Snackbar的使用

Snackbar 是 Android 5.0 新特性--Material Design 中的一个控件,用来代替 Toast ,Snackbar与Toast的主要区别是:Snackbar可以滑动退出,也可以处理用户交互(点击)事件. Snackbar的特点如下: Snackbar会在超时或者用户在屏幕其他地方触摸之后自动消失 可以在屏幕上滑动关闭 出现时不会阻碍用户在屏幕上的输入 不支持输入 屏幕上同时最多只能显示一个Snackbar 如果在屏幕上有一个Snackbar的情况下再显示一个Snack

【转】android MD设计

编者按:这一年就快完了,你还没搞懂Material design吗?是嫌文档太长,还是觉得自己英文不好?都没关系,我们善良热情的@十萬個為什麽  帮同学们通读了一遍官方的设计指南,去糙取精,整理出这篇干货超多的学习笔记,打包票学完基本就掌握90%了,别错过咯! 自从Material design发布以来,可乐橙就在一直收集相关素材与资源,研究别人的作品.这套设计风格非常鲜明,带有浓郁的Google式严谨和理性哲学,深得我心.实际上,光是研究素材和别人作品,就能发现一些明显的规律,做出几分相似的设

【Android - MD】之CardView的使用

CardView是Android 5.0新特性--Material Design中的一个布局控件,可以通过属性设置显示一个圆角的类似卡片的视图. 1.CardView的属性: app:cardCornerRadius:CardView的圆角大小 app:cardElevation:CardView的阴影大小 app:cardMaxElevation:CardView最大阴影大小 app:cardPreventCornerOverlap:CardView中的内容是否和圆角重叠,true为不重叠 注

如何使用android design support library

Android应用Design Support Library完全使用实例 - OPEN 开发经验库http://www.open-open.com/lib/view/open1433385856119.html Android MD风格相关控件小结 - 简书http://www.jianshu.com/p/5e6f2ae1d2ec 在android studio中引用这个库非常简单,只要在 build.gradle 文件中加上这段代码: compile 'com.android.support

Android CoordinatorLayout、AppBarLayout、CollapsingToolbarLayout、Toolbar 等的说明和使用

请尊重个人劳动成果,转载注明出处,谢谢! http://blog.csdn.net/amazing7/article/details/51918623 1. CoordinatorLayout 我们通常把CoordinatorLayout作为顶层布局来协调其子布局之间的动画效果. 子view1在布局中通过设置behavior属性与子view2关联,当移动view2的时候view1产生相应的效果,而这个效果具体是怎么样的由behavior类来决定.我们把view1叫做Child,view2叫做De

Android.Hook框架Cydia篇

Cydia Substrate是一个代码修改平台.它可以修改任何主进程的代码,不管是用Java还是C/C++(native代码)编写的.而Xposed只支持HOOK app_process中的java函数,因此Cydia Substrate是一款强大而实用的HOOK工具. 官网地址:http://www.cydiasubstrate.com/ 官方教程:http://www.cydiasubstrate.com/id/38be592b-bda7-4dd2-b049-cec44ef7a73b SD