如何使用Android快餐栏弹出整个片段布局

时间:2016-10-11 11:19:47

标签: android android-fragments android-snackbar

我没有任何浮动按钮,但是当我显示小吃栏时,我想弹出整个布局。为此我将片段包装到CoordinatorLayout中,如下所示:

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

    <FrameLayout
        android:id="@+id/container_for_fragments"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"/>

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

container_for_fragments托管我的碎片的地方。我声明CoordinatorLayout,然后像这样使用它:

       Snackbar snackbar = Snackbar.make(myCoordinatorLayout, "Hello", Snackbar.LENGTH_LONG);
       snackbar.show();

我得到了:enter image description here

当小吃栏出现时,有没有办法弹出整个片段?

1 个答案:

答案 0 :(得分:2)

编写自己的行为,对显示Snackbar

作出反应
public class FrameLayoutBehavior extends CoordinatorLayout.Behavior<FrameLayout> {

    private float mFrTranslationY;

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

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

    @Override
    public boolean onDependentViewChanged(final CoordinatorLayout parent, final FrameLayout child, final View dependency) {
        if (dependency instanceof Snackbar.SnackbarLayout) {
            updateFabTranslationForSnackbar(parent, child, dependency);
            ViewCompat.setTranslationY(child, mFrTranslationY);
        }
        return false;
    }

    @Override
    public void onDependentViewRemoved(final CoordinatorLayout parent, final FrameLayout child, final View dependency) {
        super.onDependentViewRemoved(parent, child, dependency);
    }

    private void updateFabTranslationForSnackbar(CoordinatorLayout parent, final FrameLayout fab, View snackbar) {
        mFrTranslationY = getFabTranslationYForSnackbar(parent, fab, snackbar);
    }

    private float getFabTranslationYForSnackbar(CoordinatorLayout parent, FrameLayout fab, View snackbar) {
        float minOffset = 0;
        minOffset = Math.min(minOffset, ViewCompat.getTranslationY(snackbar) - snackbar.getHeight());
        return minOffset;
    }
}

然后将参数app:layout_behavior添加到FrameLayout。当FrameLayoutFragment替换时,行为可能会丢失。然后你必须添加:

@CoordinatorLayout.DefaultBehavior(FrameLayoutBehavior.Behavior.class)

就在片段的类声明之上。