Android笔记

Android中View基础知识

2018-09-20  本文已影响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位置改变时
由上图得出结论

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 内容的移动位置(实际位置)。

上一篇 下一篇

猜你喜欢

热点阅读