android让控件在屏幕上自由拖动或者在一定范围内拖动

2018-03-13  本文已影响0人  谜之龙
public class Main2Activity extends AppCompatActivity {
View view1;
int y1 = 0;
int newY=0;
int dY=0;
int dX=0;
int newX=0;
int x1 = 0;
private ImageView image;
//这里是防止控件移动到自己不想去的地方,如果不需要些0或者去掉
int imageHight;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    image = (ImageView) findViewById(R.id.image);
    view1=findViewById(R.id.text2);
    image.post(new Runnable() {
        @Override
        public void run() {
            imageHight=image.getHeight();
        }
    });
    image.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            MetTouchLeftClick(motionEvent);
            return true;
        }
    });
}

private Rect mChangeImageBackgroundRect = null;
private boolean isInChangeImageZone(View view, int x, int y) {
    if (null == mChangeImageBackgroundRect) {
        mChangeImageBackgroundRect = new Rect();
    }
    view.getDrawingRect(mChangeImageBackgroundRect);
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    mChangeImageBackgroundRect.left = location[0];
    mChangeImageBackgroundRect.top = location[1];
    mChangeImageBackgroundRect.right = mChangeImageBackgroundRect.right + location[0];
    mChangeImageBackgroundRect.bottom = mChangeImageBackgroundRect.bottom + location[1];
    return mChangeImageBackgroundRect.contains(x, y);
}
private void MetTouchLeftClick(MotionEvent event){
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            //当手指按下的时候
            x1 =(int) event.getRawX();
            y1 = (int) event.getRawY();
            break;
        case MotionEvent.ACTION_MOVE:
            newY=(int) event.getRawY();
            newX=(int) event.getRawX();
            dY=newY-y1;
            dX=newX-x1;
            int l=image.getLeft();
            int t=image.getTop();
            l+=dX;
            t+=dY;
            int r=l+image.getWidth();
            int b=t+image.getHeight();
            Log.e("移动","是是是=="+t);
            if (t>0&&t<view1.getTop()-imageHight){
                image.layout(l,t,r,b);
            }

            x1=newX;
            y1=newY;
            break;
    }
}
}
上一篇下一篇

猜你喜欢

热点阅读