借鉴自Android进阶之光,刘望舒的好书!
(
此外再介绍各个阶段应该看的书:
入门 第一行代码
中阶 Android群英传(偏UI) Android进阶之光(偏业务)
高阶 Android开发艺术探索 (还有一本源代码解析好像挺不错的,不过我没看过)
)
(这里采用自定义控件的方式,接下来我会写更具体的应用场景)
自定义控件继承自View,里面就一个简单的方法,用来监听手势的,然后在布局文件中引用这个自定义控件就可以(后面我会给出完整代码)
public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = x - lastX; int offsetY = y - lastY; //1.layout //getTop()就是顶部距离父容器顶部, //getTop()就是底部距离父容器顶部 // layout(getLeft() + offsetX, getTop() + offsetY, // getRight() + offsetX, getBottom() + offsetY); //2.offsetLeftAndRight() //类似方法1 // offsetLeftAndRight(offsetX); // offsetTopAndBottom(offsetY); //3.改变布局参数(1)LayoutParams(根据不同父布局选择),这里是ConstraintLayout //(2)ViewGroup的MarginLayoutParams //测试发现用不了 // ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) // getLayoutParams(); // ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) //