Android自定义View

Android的View中比较有用的几个方法

2016-11-08  本文已影响310人  千山万水迷了鹿
  1. getParent().requestDisallowInterceptTouchEvent(true);
    //屏蔽父控件拦截onTouch事件

  2. 动态创建View的时候,获取View的大小

TextView mTextView = new TextView(this);
mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
mTextView.setText("hhhhhhhhh");
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
mTextView.measure(spec, spec);
// getMeasuredWidthint
measuredWidth = mTextView.getMeasuredWidth();
```

  1. getWidth()和getMeasuredWidth()

    getWidth(): **
    得到的是view在父Layout中布局好后的宽度值,如果没有父布局,那么默认的父布局就是整个屏幕。
    注意这个没有set方法**。

    ** getMeasuredWidth():**
    得到的是最近一次调用measure(int,int)方法测量后得到的是View的宽度,它仅仅用在测量和Layout的计算中。所以此方法得到的是View的内容占据的实际宽度

  2. getX() getLeft() 和 getTranslationX()

盗图一张
public void setX(float x) {
        setTranslationX(x - mLeft);
    }
  1. View 的几个重要方法

    requestLayout:View重新调用一次layout过程

    invalidate:View重新调用一次draw过程

    forceLayout:标识View在下一次重绘,需要重新调用layout过程。

    postInvalidate:这个方法与invalidate方法的作用是一样的,都是使View树重绘,但两者的使用条件不同,postInvalidate是在非UI线程中调用,invalidate则是在UI线程中调用。

  2. 理解MeasureSpec三种模式

View的大小不仅由自身所决定,同时也会受到父控件的影响,为了我们的控件能更好的适应各种情况,一般会自己进行测量。他们是由 mode+size两部分组成的。widthMeasureSpec和heightMeasureSpec转化成二进制数字表示,他们都是30位的。前两位代表mode(测量模 式),后面28位才是他们的实际数值(size);MeasureSpec.getMode()获取模式,MeasureSpec.getSize()获取尺寸
测量View大小使用的是onMeasure函数,所以我们需要了解三种测量模式:

  1. measure(int widthMeasureSpec, int heightMeasureSpec)方法会调用onMeasure(widthMeasureSpec, heightMeasureSpec);方法

  2. view.anim
    Android3.0 之后,Google给View增加了animate方法来直接驱动 属性动画,它可以被认为是属性动画的一种简写方式。
    实例代码:view.animate().x(500).y(500).setDuration(5000);
    注释:操作的是View中的一个成员变量

   /**
     * Object that handles automatic animation of view properties.
     */
    private ViewPropertyAnimator mAnimator = null;
上一篇下一篇

猜你喜欢

热点阅读