Moving buttons via Touch

前端 未结 1 1163
逝去的感伤
逝去的感伤 2020-12-09 14:10

I want to move my buttons to another palce with touch. I mean if user touch one button and go to another place via touch, the button moves. I write this code for one of butt

相关标签:
1条回答
  • 2020-12-09 14:27

    Create a new Class that implements OnTouchListener

    import android.annotation.SuppressLint;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnTouchListener;
    import android.view.ViewGroup.MarginLayoutParams;
    import android.widget.RelativeLayout;
    
    public class MultiTouchListener implements OnTouchListener
    {
    
    private float mPrevX;
    private float mPrevY;
    
    public MainActivity mainActivity;
    public MultiTouchListener(MainActivity mainActivity1) {
        mainActivity = mainActivity1;
    }
    
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        float currX,currY;
        int action = event.getAction();
        switch (action ) {
            case MotionEvent.ACTION_DOWN: {
    
                mPrevX = event.getX();
                mPrevY = event.getY();
                break;
            }
    
            case MotionEvent.ACTION_MOVE:
            {
    
                    currX = event.getRawX();
                    currY = event.getRawY();
    
    
                    MarginLayoutParams marginParams = new MarginLayoutParams(view.getLayoutParams());   
                    marginParams.setMargins((int)(currX - mPrevX), (int)(currY - mPrevY),0, 0);
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
                    view.setLayoutParams(layoutParams); 
    
    
                break;
            }
    
    
    
            case MotionEvent.ACTION_CANCEL:
                break;
    
            case MotionEvent.ACTION_UP:
    
                break;
        }
    
        return true;
    }
    
    }
    

    Now in your Main activity, set OnTouchListener on your view... that is your imageButton or imageView;

    MultiTouchListener touchListener=new MultiTouchListener(this);
    onButton.setOnTouchListener(touchListener);
    
    0 讨论(0)
提交回复
热议问题