android – 浮动动作按钮意外锚定重力变化

我有一个活动和几个片段.其中一个片段包含具有锚重力底部的FAB.它看起来不错,但是当我开始另一个片段然后按回按钮时,我的FAB出现在左上角.我使用协调器布局,但它没有帮助.这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/fragment_main_page">

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/main_page_listview"
    android:layout_marginTop="5dp">

</ListView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="3dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:src="@drawable/info_main_page"
        android:layout_gravity="center_vertical"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_gravity="center_vertical"
        android:id="@+id/how_to_use"
        android:text="@string/how_to_use"
        android:textAllCaps="false"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="italic"
        android:background="@android:color/transparent"/>

</LinearLayout>

</LinearLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/floating_promos"
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/floating_promos"
    app:layout_anchor="@id/fragment_main_page"
    app:layout_anchorGravity="bottom|right|end"
    app:backgroundTint="#fb9f12"
    app:fabSize="mini"/>
   </android.support.design.widget.CoordinatorLayout>

最佳答案 我做了一个小调整以使其工作,因为我需要我只是添加了监听器来检查回收器视图是否更新并在其中更改了FAB.

希望这会帮助你.

listWorkData.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        listWorkData.removeOnLayoutChangeListener(this);

        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) btnSubmitConfirm.getLayoutParams();
        lp.anchorGravity = Gravity.BOTTOM | GravityCompat.END;
        btnSubmitConfirm.setLayoutParams(lp);
    }
});

listWorkData.getAdapter().notifyDataSetChanged();
点赞