En este enlace hay la solución para ocular y mostrar el fab button FloatingActionButton
dependiendo del scroll
Pero me gustaría que cuando se oculte y mostrase el fab button lo hiciera con una animación slide Arriba y Abajo:
Stack Overflow en español es un sitio de preguntas y respuestas para programadores y profesionales de la informática. Solo te toma un minuto registrarte.
Regístrate para unirte a esta comunidadEn este enlace hay la solución para ocular y mostrar el fab button FloatingActionButton
dependiendo del scroll
Pero me gustaría que cuando se oculte y mostrase el fab button lo hiciera con una animación slide Arriba y Abajo:
Puedes hacerlo de dos formas, utilizando una clase que extienda de FloatingActionButton.Behavior
y enlazándolo con la view del Floating Action Button
en el XML
o programandolo directamente en el RecyclerView
.
Te voy a enseñar las dos formas y tu eliges la que más te guste.
PRIMER MÉTODO
Cuando busqué como hacer justo lo que tu estas preguntando, todo lo que aparecía utilizaban el mismo método. Creaban una nueva clase java y extendían de FloatingActionButton.Behavior
para detectar el movimiento de la ListView
o RecyclerView
(lo que utilices) y luego enlazan esta misma clase con el view del Floating Action Button
(FAB
) de la siguiente forma:
Clase FABMove.java
:
public class FABMove extends FloatingActionButton.Behavior {
public FABMove(Context context, AttributeSet attrs) {
super();
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0) {
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
int margin = layoutParams.bottomMargin;
child.animate().translationY(child.getHeight() + margin).setInterpolator(new LinearInterpolator()).setDuration(1000).start();
} else if (dyConsumed < 0) {
child.animate().translationY(0).setInterpolator(new LinearInterpolator()).setDuration(1000).start();
}
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
}
}
Y ahora, solo tienes que ir al archivo XML
donde tengas declarado el FAB
y añadir un CoordinatorLayout
encapsulando tu RecyclerView
y el FAB
y a este le añades la propiedad app:layout_behavior
que enlaza con tu clase java:
<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">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:layout_anchor="@+id/recycler_view"
app:layout_anchorGravity="bottom|end"
app:layout_behavior="com.victoria.fabsmove.FABMove" />
</android.support.design.widget.CoordinatorLayout>
Listo!
SEGUNDO MÉTODO:
Este método, para mi, lo veo relativamente sencillo, mucho más que el primero porque no se tiene que crear tantas cosa. Simplemente tienes que agregar la función addOnScrollListener()
al RecyclerView
y sobrescribir el método onScrolled()
para que detecte el movimiento de la lista.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
if (dy > 0)
// Puedes ocultarlo simplemente
//fab.hide();
// o añadir la animación deseada
fab.animate().translationY(fab.getHeight() +
getResources().getDimension(R.dimen.fab_margin))
.setInterpolator(new LinearInterpolator())
.setDuration(1000); // Cambiar al tiempo deseado
else if (dy < 0)
//fab.show();
fab.animate().translationY(0)
.setInterpolator(new LinearInterpolator())
.setDuration(1000); // Cambiar al tiempo deseado
}
});
Con esto ya estaría todo listo. Si tienes alguna duda avisa enseguida.
Aún así, la respuesta que ha dado nuestro compañero Andres Gillermo Castellanos A (link), porque además te enseñas a crear menús directamente en el FAB
y es muy interesante.
Mucha suerte con tu app!!
Compañero, en este sitio https://www.sitepoint.com/animating-android-floating-action-button/ encontrara la respuesta paso a paso y ademas puede descargar el ejemplo que se encuentra en este git https://github.com/sitepoint-editors/FloatingActionButton_Animation_Project
Espero haberle ayudado.
Mi solución usando FloatingActionButton.Behavior
adaptando el código de la respuesta @Vicky_Vicent
Añado un flag
para saber si la animación está en curso, para evitar sobrecarga de animación.
public class AboutFabScrollBehavior extends FloatingActionButton.Behavior {
private boolean startAnimation = false;
public AboutFabScrollBehavior(Context context, AttributeSet attributeSet) {
super();
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, final FloatingActionButton child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
if (!startAnimation) {
Interpolator interpolador = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
interpolador = AnimationUtils.loadInterpolator(MyApplication.getAppContext(),
android.R.interpolator.fast_out_linear_in);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
child.animate()
//.translationYBy(0f)
.translationY(child.getHeight() +
child.getContext().getResources().getDimension(R.dimen.fab_margin))
.setInterpolator(interpolador)
.setDuration(child.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
child.setVisibility(View.GONE);
startAnimation = false;
}
})
.start();
}
startAnimation = true;
}
} else if (dyConsumed < 0 && child.getVisibility() == View.GONE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
if (!startAnimation) {
child.setVisibility(View.VISIBLE);
Interpolator interpolador = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
interpolador = AnimationUtils.loadInterpolator(MyApplication.getAppContext(),
android.R.interpolator.fast_out_linear_in);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
child.animate()
// .translationYBy(150f)
.translationY(0f)
.setInterpolator(interpolador)
.setDuration(child.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
startAnimation = false;
}
})
.start();
}
Animation animation = AnimationUtils.loadAnimation(MyApplication.getAppContext(),
R.anim.fade_in);
child.startAnimation(animation);
}
}
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
//return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
}
}