如何按住浮动按钮并将其移动到Android屏幕上的任何位置?

时间:2015-12-28 07:04:12

标签: android layout floating-action-button

我在屏幕右下角的Android应用程序中添加了一个浮动按钮。我希望用户能够按住浮动按钮并将其移动到屏幕上的任何其他位置。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用WindowManager实现它,就像在onCreate中添加此代码一样:

windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
floatingbutton= (ImageView)findViewById(R.id.floating_button);
 final LayoutParams myParams = new WindowManager.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT,
        LayoutParams.TYPE_PHONE,
        LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);

    myParams.gravity = Gravity.TOP | Gravity.LEFT;
    myParams.x=0;
    myParams.y=100;

    windowManager.addView(floatingbutton, myParams);

floatingbutton.setOnTouchListener(new View.OnTouchListener() {
 private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;
  @Override
            public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){


                     case MotionEvent.ACTION_DOWN:
                        touchStartTime = System.currentTimeMillis();
                        handler_longClick.postDelayed(runnable_longClick, 600);
                         initialX = myParams.x;
                         initialY = myParams.y;
                         initialTouchX = event.getRawX();
                         initialTouchY = event.getRawY();
                      //   System.out.println("in ACTION_DOWN");

                         break;
   case MotionEvent.ACTION_UP:
                         System.out.println("in ACTION_UP");

break;
 case MotionEvent.ACTION_MOVE:

                        int x_cord = (int) event.getRawX();
                        int y_cord = (int) event.getRawY();
                         myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
                         myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
                         windowManager.updateViewLayout(v, myParams);
 break;
 }
         return false;
            }
        });