我在我的应用程序中使用了FloatingActionButton。偶尔会与重要内容重叠,因此我希望用户可以将FAB移到一边。
不需要拖放功能,只需要可移动即可。文档没有提到这一点,但我确定我在其他应用程序中看到过这种功能。
您能否提供建议/代码片段来执行此操作(最好是在XML中)?
我在我的应用程序中使用了FloatingActionButton。偶尔会与重要内容重叠,因此我希望用户可以将FAB移到一边。
不需要拖放功能,只需要可移动即可。文档没有提到这一点,但我确定我在其他应用程序中看到过这种功能。
您能否提供建议/代码片段来执行此操作(最好是在XML中)?
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:id="@+id/dashboardShowActionsFab"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
JAVA
fab.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
int action = motionEvent.getAction();
if (action == MotionEvent.ACTION_DOWN) {
downRawX = motionEvent.getRawX();
downRawY = motionEvent.getRawY();
dX = view.getX() - downRawX;
dY = view.getY() - downRawY;
return true; // Consumed
} else if (action == MotionEvent.ACTION_MOVE) {
int viewWidth = view.getWidth();
int viewHeight = view.getHeight();
View viewParent = (View) view.getParent();
int parentWidth = viewParent.getWidth();
int parentHeight = viewParent.getHeight();
float newX = motionEvent.getRawX() + dX;
newX = Math.max(layoutParams.leftMargin, newX); // Don't allow the FAB past the left hand side of the parent
newX = Math.min(parentWidth - viewWidth - layoutParams.rightMargin, newX); // Don't allow the FAB past the right hand side of the parent
float newY = motionEvent.getRawY() + dY;
newY = Math.max(layoutParams.topMargin, newY); // Don't allow the FAB past the top of the parent
newY = Math.min(parentHeight - viewHeight - layoutParams.bottomMargin, newY); // Don't allow the FAB past the bottom of the parent
view.animate()
.x(newX)
.y(newY)
.setDuration(0)
.start();
return true; // Consumed
} else if (action == MotionEvent.ACTION_UP) {
float upRawX = motionEvent.getRawX();
float upRawY = motionEvent.getRawY();
float upDX = upRawX - downRawX;
float upDY = upRawY - downRawY;
if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
// return performClick();
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
} else { // A drag
return true; // Consumed
}
} else {
//return super.onTouchEvent(motionEvent);
}
return true;
}