CoordinatorLayout忽略具有锚点的视图的边距。

32

假设我使用了以下这种布局:

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

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/flexible_space_image_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:statusBarScrim="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                />

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

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/mainView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginBottom="20dp"
        app:fabSize="normal"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|center_horizontal"
        />

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

这基本上是标准的Cheesesquare示例,除了我想将FloatingActionButton向上移动约20dp。

然而,这样做是不起作用的。无论我使用margin、padding等,按钮始终会居中于锚点边缘,如下所示:

FAB将忽略边距

我该如何像预期的那样将FAB向上移动20dp?


报告在 https://code.google.com/p/android/issues/detail?id=176096。 - Sebastian Roth
这个bug发生在哪个API版本中? - lf215
7个回答

36

我为你提出一个优雅的解决方案:

<android.support.design.widget.FloatingActionButton
    ...
    android:translationY="-20dp"
    ...
/>

1
考虑到整体布局性能,应将此标记为解决方案。不要使用不必要的线性布局。 - MEX
1
这让我大吃一惊!如此简单,以前从未在布局中使用过翻译!肯定会在其他棘手的情况下帮助我。 - Fabio

14

尝试将其放入具有填充的线性布局中:

<LinearLayout
  width=".."
  height=".."
  paddingBottom="20dp"
  app:layout_anchor="@id/appbar"
  app:layout_anchorGravity="bottom|center_horizontal">

  <android.support.design.widget.FloatingActionButton
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:fabSize="normal" />

</LinearLayout>

1
谢谢。很不错,但是:LinearLayout未声明@DefaultBehavior,这将禁用与父CoordinatorLayout的交互。至于FAB,我相信你已经看到了“奶酪正方形”演示:一旦达到滚动阈值,它将以动画方式退出。我仍然希望有这个功能,只是底部多一点外边距。 - Sebastian Roth
关于 FloatingActionButton,使用内边距(padding)而不是外边距(margin)怎么样? - hasan
4
尝试过,但没有成功。似乎一旦设置了这种行为,边距和填充几乎被完全忽略了。 - Sebastian Roth

3
作为设计支持库中可能会涉及CoordinatorLayout和边距的错误,我编写了一个FrameLayout,实现/复制了与FAB相同的“Behavior”,并允许设置padding来模拟该效果:
请确保将其放置在android.support.design.widget包中,因为它需要访问一些包范围内的类。
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;

import com.company.android.R;

import java.util.List;

@CoordinatorLayout.DefaultBehavior(FrameLayoutWithBehavior.Behavior.class)
public class FrameLayoutWithBehavior extends FrameLayout {
    public FrameLayoutWithBehavior(final Context context) {
        super(context);
    }

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

    public FrameLayoutWithBehavior(final Context context, final AttributeSet attrs, final int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public FrameLayoutWithBehavior(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public static class Behavior extends android.support.design.widget.CoordinatorLayout.Behavior<FrameLayoutWithBehavior> {
        private static final boolean SNACKBAR_BEHAVIOR_ENABLED;
        private Rect mTmpRect;
        private boolean mIsAnimatingOut;
        private float mTranslationY;

        public Behavior() {
        }

        @Override
        public boolean layoutDependsOn(CoordinatorLayout parent, FrameLayoutWithBehavior child, View dependency) {
            return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
        }

        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, FrameLayoutWithBehavior child, View dependency) {
            if (dependency instanceof Snackbar.SnackbarLayout) {
                this.updateFabTranslationForSnackbar(parent, child, dependency);
            } else if (dependency instanceof AppBarLayout) {
                AppBarLayout appBarLayout = (AppBarLayout) dependency;
                if (this.mTmpRect == null) {
                    this.mTmpRect = new Rect();
                }

                Rect rect = this.mTmpRect;
                ViewGroupUtils.getDescendantRect(parent, dependency, rect);
                if (rect.bottom <= appBarLayout.getMinimumHeightForVisibleOverlappingContent()) {
                    if (!this.mIsAnimatingOut && child.getVisibility() == VISIBLE) {
                        this.animateOut(child);
                    }
                } else if (child.getVisibility() != VISIBLE) {
                    this.animateIn(child);
                }
            }

            return false;
        }

        private void updateFabTranslationForSnackbar(CoordinatorLayout parent, FrameLayoutWithBehavior fab, View snackbar) {
            float translationY = this.getFabTranslationYForSnackbar(parent, fab);
            if (translationY != this.mTranslationY) {
                ViewCompat.animate(fab)
                          .cancel();
                if (Math.abs(translationY - this.mTranslationY) == (float) snackbar.getHeight()) {
                    ViewCompat.animate(fab)
                              .translationY(translationY)
                              .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
                              .setListener((ViewPropertyAnimatorListener) null);
                } else {
                    ViewCompat.setTranslationY(fab, translationY);
                }

                this.mTranslationY = translationY;
            }

        }

        private float getFabTranslationYForSnackbar(CoordinatorLayout parent, FrameLayoutWithBehavior fab) {
            float minOffset = 0.0F;
            List dependencies = parent.getDependencies(fab);
            int i = 0;

            for (int z = dependencies.size(); i < z; ++i) {
                View view = (View) dependencies.get(i);
                if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(fab, view)) {
                    minOffset = Math.min(minOffset, ViewCompat.getTranslationY(view) - (float) view.getHeight());
                }
            }

            return minOffset;
        }

        private void animateIn(FrameLayoutWithBehavior button) {
            button.setVisibility(View.VISIBLE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                ViewCompat.animate(button)
                          .scaleX(1.0F)
                          .scaleY(1.0F)
                          .alpha(1.0F)
                          .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
                          .withLayer()
                          .setListener((ViewPropertyAnimatorListener) null)
                          .start();
            } else {
                Animation anim = android.view.animation.AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_in);
                anim.setDuration(200L);
                anim.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
                button.startAnimation(anim);
            }

        }

        private void animateOut(final FrameLayoutWithBehavior button) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                ViewCompat.animate(button)
                          .scaleX(0.0F)
                          .scaleY(0.0F)
                          .alpha(0.0F)
                          .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
                          .withLayer()
                          .setListener(new ViewPropertyAnimatorListener() {
                              public void onAnimationStart(View view) {
                                  Behavior.this.mIsAnimatingOut = true;
                              }

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

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

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

        }

        static {
            SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
        }
    }
}

3

一个简单的解决方法是将一个随机布局锚定到FAB所在的位置,给它指定的边距,然后将FAB锚定到随机布局上,就像这样:

<LinearLayout
 android:orientation="horizontal"
 android:id="@+id/fab_layout"
 android:layout_width="5dp"
 android:layout_height="5dp"
 android:layout_marginRight="80dp"
 android:layout_marginEnd="80dp"
 app:layout_anchor="@id/collapsing_toolbar"
 app:layout_anchorGravity="bottom|end"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_map"
    app:layout_anchor="@id/fab_layout"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"
 />

1

要将FloatingActionButton定位在AppBar下方,如下所示: Fab as anchor to the AppBar

扩展FloatingActionButton并覆盖offsetTopAndBottom

public class OffsetFloatingActionButton extends FloatingActionButton
{
    public OffsetFloatingActionButton(Context context)
    {
        this(context, null);
    }

    public OffsetFloatingActionButton(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public OffsetFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom)
    {
        super.onLayout(changed, left, top, right, bottom);
        ViewCompat.offsetTopAndBottom(this, 0);
    }

    @Override
    public void offsetTopAndBottom(int offset)
    {
        super.offsetTopAndBottom((int) (offset + (getHeight() * 0.5f)));
    }
}

这种方法可以使fab与缝合处产生偏移,但会破坏隐藏/显示动画,因为动画不知道偏移量。 - zyamys

0

我能通过同时使用layout_anchorlayout_anchorGravity以及一些填充来解决这个问题。锚属性允许您将一个View相对于另一个视图定位。但是,它的工作方式并不完全像RelativeLayout那样。后续更多内容。

layout_anchor指定应该定位您所需的View的哪个View(即,此View应该相对于layout_anchor属性指定的View放置)。然后,layout_anchorGravity使用典型的Gravity值(topbottomcenter_horizontal等)指定当前View将被放置在相对View的哪一侧。

仅使用这两个属性的问题在于,带有锚点的View中心将相对于其他View放置。例如,如果您指定一个FloatingActionButton锚定到TextView的底部,实际上发生的是FAB的中心沿着TextView的底部边缘放置。
为了解决这个问题,我对FAB应用了一些填充,足够使FAB的顶部边缘接触到TextView的底部边缘:
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_anchor="@id/your_buttons_id_here"
    android:layout_anchorGravity="bottom"
    android:paddingTop=16dp" />

你可能需要增加填充来达到所需的效果。希望能帮到你!


0

我在FAB中使用了app:useCompatPadding="true",一切都正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接