Android - move an ImageView on screen (Like dragging)

前端 未结 6 1196
灰色年华
灰色年华 2021-02-05 15:34

I\'m trying to create an app that can move an ImageView on your device like dragging and when I put like 75% of the ImageView out of the screen show a

6条回答
  •  孤街浪徒
    2021-02-05 16:26

    A working example of how to move all the views contained in a RelativeLayout using onTouch. Hope it will help :

    public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
        private RelativeLayout mRelLay;
        private float mInitialX, mInitialY;
        private int mInitialLeft, mInitialTop;
        private View mMovingView = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mRelLay = (RelativeLayout) findViewById(R.id.relativeLayout);
    
            for (int i = 0; i < mRelLay.getChildCount(); i++)
                mRelLay.getChildAt(i).setOnTouchListener(this);
        }
    
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            RelativeLayout.LayoutParams mLayoutParams;
    
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mMovingView = view;
                    mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams();
                    mInitialX = motionEvent.getRawX();
                    mInitialY = motionEvent.getRawY();
                    mInitialLeft = mLayoutParams.leftMargin;
                    mInitialTop = mLayoutParams.topMargin;
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    if (mMovingView != null) {
                        mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams();
                        mLayoutParams.leftMargin = (int) (mInitialLeft + motionEvent.getRawX() - mInitialX);
                        mLayoutParams.topMargin = (int) (mInitialTop + motionEvent.getRawY() - mInitialY);
                        mMovingView.setLayoutParams(mLayoutParams);
                    }
                    break;
    
                case MotionEvent.ACTION_UP:
                    mMovingView = null;
                    break;
            }
    
            return true;
        }
    }
    

提交回复
热议问题