一个跟随手指滑动的Button

最近在看《Android开发艺术探索》,第三章有个跟随手指滑动的示例,他是用开源动画库做的,我用Margin属性写了一个

代码如下

public class MainActivity extends AppCompatActivity implements View.OnTouchListener{

    private Button button;
    private int x,y;
    private int DeltaX = 0,DeltaY = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnTouchListener(this);
    }

    public boolean onTouch(View view, MotionEvent event) {
        x = (int) event.getRawX();
        y = (int) event.getRawY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                RelativeLayout.LayoutParams parmas1 = (RelativeLayout.LayoutParams) view.getLayoutParams();
                DeltaX = x-parmas1.leftMargin;
                DeltaY = y-parmas1.topMargin;
                break;
            case MotionEvent.ACTION_MOVE:
                RelativeLayout.LayoutParams parmas2 = (RelativeLayout.LayoutParams) view.getLayoutParams();
                parmas2.leftMargin = x - DeltaX;
                parmas2.topMargin = y - DeltaY;

                view.setLayoutParams(parmas2);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        view.invalidate();
        return true;
    }
}

其中DeltaX,DeltaY其实时控件内部的距离,因为leftMargin和topMargin设置的是控件的左上角,用手指坐标减去控件内部坐标就是控件左上角坐标了

你可能感兴趣的:(我的学习笔记)