View的滑动

view的滑动方法有3种:

  1. scrollTo();scrollBy();
  2. 动画(view动画和属性动画)
  3. 动态改变margin

区别:

  1. scrollTo();scrollBy();改变的是view中内容的位置,view的布局参数未改变
  2. 动画改变的是view的影像,也没改变view的布局参数.并且在新的位置,不会响应点击事件.
  3. Android3.0后通过属性动画可以解决点击事件不移动的问题

使用场景:

  1. scrollTo/scrollBy适合对view内容滑动
  2. 动画适合没有交互和实现复杂的动画效果
  3. 动态margin适合带交互的view

动态margin伪代码

MarginLayoutParams params = (MarginLayoutParams)mButton1.getLayoutParams();
    params.width += 100;
    params.leftMargin += 100;
    mButton1.requestLayout();
    //或者mButton1.setLayoutParams(params);

基于动画自定义view,实现view跟随手指移动

首先需要导入属性动画库nineoldandroids

implementation 'com.nineoldandroids:library:2.4.0'

下面是实现代码

public class MoveView extends AppCompatImageView {
    public MoveView(Context context) {
        this(context, null);
    }

    public MoveView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private float lastX, lastY;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        float rawX = ev.getRawX();
        float rawY = ev.getRawY();
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:

                break;
            case MotionEvent.ACTION_MOVE:
                float dealX = rawX - lastX;
                float dealY = rawY - lastY;
                ViewHelper.setTranslationX(this, getTranslationX() + dealX);
                ViewHelper.setTranslationY(this, getTranslationY() + dealY);
                break;
            case MotionEvent.ACTION_UP:

                break;
        }
        lastX = rawX;
        lastY = rawY;
        return true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容