美文网首页Android笔记
Android中View基础知识

Android中View基础知识

作者: 夕阳骑士 | 来源:发表于2018-09-20 10:53 被阅读0次

1. View的宽高

Android中View的位置主要由 top, lef, bottom, right 四个顶点确定, 如下图所示:

view的宽高坐标
int top = view.getTop();        // view的顶部距父控件顶部的距离
int bottom = view.getBottom();  // view的底部距父控件顶部的距离
int left = view.getLeft();      // view的左边距父控件左边的距离
int right = view.getRight();    // view的右边距父控件右边的距离
int width = view.getWidth();    // view的宽度
int height = view.getHeight();  // view的高度

结论1:width = view.getBottom() - view.getTop(),height = view.getRight() - view.getLeft()


2. View的坐标及MotionEvent

在处理事件时我们经常需要获取View的坐标,触摸事件onTouchEvent(MotionEvent event)的参数MotionEvent中,我们可以拿到View的相关坐标,如下图所示:

MotionEvent坐标
float rawX = event.getRawX();   // 触摸点相对手机屏幕的x坐标
float rawY = event.getRawY();   // 触摸点相对手机屏幕的y坐标
float getx = getX();            // 触摸点相对view自己的x坐标
float gety = getY();            // 触摸点相对view自己的y坐标

3. View的位置改变时

view位置改变时
由上图得出结论
  • top、left、right、bottom代表View的初始坐标,在绘制完毕后就不会再改变
  • translationX、translationY代表View左上角的偏移量(相对于父容器),比如上图是View进行了平移,那么translation代表水平平移的像素值,translationY代表竖直平移的像素值
  • x、y代表当前View左上角相对于父容器的坐标,即实时相对坐标
  • 以上参数的关系可以用这两个公式表示:x = left + translationXy = top+ translationY

4. scrollTo和scrollBy的区别

先来看看源码

   /**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }

    /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }

首先必须明确: scrollTo 和 scrollBy 都只能让 View 的内容移动, View 自身不会移动,如果 View 内容已不可移动,则调用无效。

从源码可以看出
scrollBy 也是调用 scrollTo 方法,他们唯一的区别就是 scrollBy 传入的是 iew 的内容在水平方向和垂直方向的移动距离(偏移量)。 scrollTo 传入的是 View 内容的移动位置(实际位置)。

相关文章

网友评论

    本文标题:Android中View基础知识

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