First, you need to have the layout with the floating action button anchored to the ViewPager:
<android.support.design.widget.CoordinatorLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/action_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
app:tabGravity="center"
app:tabIndicatorColor="?attr/colorAccent"
app:tabMode="scrollable"
app:tabSelectedTextColor="?attr/colorAccent"
app:tabTextColor="@android:color/black" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
app:layout_anchor="@id/viewpager"
app:layout_anchorGravity="bottom|right|end"
android:layout_width="56dp"
android:layout_height="56dp"
android:src="@drawable/ic_add_white"
app:borderWidth="@dimen/fab_border_width"
app:fabSize="normal" />
</android.support.design.widget.CoordinatorLayout>
Now that you have the FAB anchored to the ViewPager (note: I've tried this on a fragment that is a tab in the viewpager; it does not seem to behave properly), add an OnPageChangeListener to your ViewPager like so:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case INDEX_OF_TAB_WITH_FAB:
fab.show();
break;
default:
fab.hide();
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
The animations for the "pop" and the "shrink" upon switching tabs are handled automatically for you with the new version of the Support Library.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…