Android: 如何在 xml 布局中 hide/show 浮动操作按钮 (fab)

Android: How can we hide/show floating action button(fab) in xml layout

我的 Activity 中有一个浮动操作按钮。我能够以编程方式 show/hide fab 按钮:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.show()
fab.hide()

但我无法在 xml 布局中设置这些属性。我在 xml 中找不到任何设置它默认隐藏的东西。这是我的 xml 布局。

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:src="@drawable/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        app:layout_anchor="@id/list_view"
        app:layout_anchorGravity="bottom|right|end" />

更新:我不想将我的 fab 按钮可见性设置为 GONE。我想在 XML 布局中设置 hide()。我想在延迟后调用 activity 中 fab 的 show() 。

在"FloatingActionButtonLollipop.java"和"FloatingActionButtonEclairMr1.java"中, show() 先检查它的可见性然后播放动画。

if (mView.getVisibility() != View.VISIBLE || mIsHiding) {
        // If the view is not visible, or is visible and currently being hidden, run
        // the show animation
        mView.clearAnimation();
        mView.setVisibility(View.VISIBLE);
        Animation anim = android.view.animation.AnimationUtils.loadAnimation(
                mView.getContext(), R.anim.design_fab_in);
        anim.setDuration(SHOW_HIDE_ANIM_DURATION);
        anim.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
        anim.setAnimationListener(new AnimationListenerAdapter() {
            @Override
            public void onAnimationEnd(Animation animation) {
                if (listener != null) {
                    listener.onShown();
                }
            }
        });
        mView.startAnimation(anim);
    } 

我认为您可以简单地将可见性设置为消失。

FloatingActionButton show()调用动画效果需要使用visibility="invisible",所以按钮的视图布局在布局中.

查看支持库中show方法的实现:

void show(@Nullable final InternalVisibilityChangedListener listener, final boolean fromUser) {
        if (isOrWillBeShown()) {
            // We either are or will soon be visible, skip the call
            return;
        }

        mView.animate().cancel();

        if (shouldAnimateVisibilityChange()) {
            mAnimState = ANIM_STATE_SHOWING;
...

和方法

private boolean shouldAnimateVisibilityChange() {
    return ViewCompat.isLaidOut(mView) && !mView.isInEditMode();
}

简单的方法是在 RelativeLayoutLinearLayout 中添加 FloatingActionButton,然后对容器布局使用 GONE/VISIBLE 操作。

  android:visibility="invisible"

我在 xml 上试过这个并简单地调用了 fab.show() 它在我的设备中使用动画。 (Android 5.1.1)