Skip to content

Instantly share code, notes, and snippets.

@PPartisan
Created October 26, 2015 13:22
Show Gist options
  • Save PPartisan/de4efb0e95c5e5c62385 to your computer and use it in GitHub Desktop.
Save PPartisan/de4efb0e95c5e5c62385 to your computer and use it in GitHub Desktop.
Auto-Hide Behaviour for the Design Support Library FloatingActionButton
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
public class FloatingActionButtonBehavior {
private static final int TOUCH_SLOP = 50;
private FloatingActionButton mFloatingActionButton;
private int startY, finalY;
private int eventY;
public FloatingActionButtonBehavior(@NonNull FloatingActionButton floatingActionButton) {
mFloatingActionButton = floatingActionButton;
init();
}
private void init() {
WindowManager wm = (WindowManager) mFloatingActionButton.getContext()
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
startY = (int) mFloatingActionButton.getY();
finalY = metrics.heightPixels;
}
public void animate(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
eventY = (int)event.getY();
break;
case MotionEvent.ACTION_MOVE:
if (event.getY() - eventY > TOUCH_SLOP) {
animateOff();
} else if (event.getY() + TOUCH_SLOP < eventY) {
animateOn();
}
break;
}
}
//Could add option to start immediately for API > 14?
private void animateOn() {
mFloatingActionButton
.animate()
.translationY(finalY)
.setInterpolator(new AccelerateInterpolator());
}
//Could add option to start immediately for API > 14?
private void animateOff() {
mFloatingActionButton
.animate()
.translationY(startY)
.setInterpolator(new DecelerateInterpolator());
}
}
/**
* Sample implementation in Activity class
*/
public class MainActivity extends AppCompatActivity {
private FloatingActionButton mFloatingActionButton;
private FloatingActionButtonBehavior mFloatingActionButtonBehavior;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
mFloatingActionButtonBehavior = new FloatingActionButtonBehavior(mFloatingActionButton);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
mFloatingActionButtonBehavior.animate(ev);
return super.dispatchTouchEvent(ev);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment