美文网首页
View的滑动

View的滑动

作者: 喝了小酒的 | 来源:发表于2021-04-09 17:52 被阅读0次

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;
    }
}

相关文章

网友评论

      本文标题:View的滑动

      本文链接:https://www.haomeiwen.com/subject/hnhwkltx.html