android: move a view on touch move (ACTION_MOVE)

后端 未结 11 2388
终归单人心
终归单人心 2020-11-22 13:54

I\'d like to do a simple control: a container with a view inside. If I touch the container and I move the finger, I want to move the view to follow my finger.

What

11条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 14:13

    Touch the container and the view will follow your finger.

    xml code

    
    
    
        
    
    
    

    Java code

    public class DashBoardActivity extends Activity implements View.OnClickListener, View.OnTouchListener {
    
        float dX;
        float dY;
        int lastAction;
        LinearLayout floatingLayout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
    
            floatingLayout = findViewById(R.id.floating_layout);
            floatingLayout.setOnTouchListener(this);    
    
    
    
         @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    dX = view.getX() - event.getRawX();
                    dY = view.getY() - event.getRawY();
                    lastAction = MotionEvent.ACTION_DOWN;
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    view.setY(event.getRawY() + dY);
                    view.setX(event.getRawX() + dX);
                    lastAction = MotionEvent.ACTION_MOVE;
                    break;
    
                case MotionEvent.ACTION_UP:
                    if (lastAction == MotionEvent.ACTION_DOWN)
                        Toast.makeText(DashBoardActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
                    break;
    
                default:
                    return false;
            }
            return true;
        }
    }
    

提交回复
热议问题