一、簡(jiǎn)述
View是Android中所有控件的基類(lèi),不管是簡(jiǎn)單的Button和TextView,還是復(fù)雜的RelativeLayout和ListView,其基類(lèi)都是View類(lèi);ViewGroup也繼承了View類(lèi),這意味著View本身就可以代表簡(jiǎn)單的和復(fù)雜的所有控件和布局,通過(guò)這種關(guān)系,就形成了View樹(shù)的結(jié)構(gòu)。
本文Demo都是在自定義View中進(jìn)行的,文末有下載鏈接
二、View的位置參數(shù)

1、原始位置(不受偏移量影響,單位是像素px)
2、寬高和坐標(biāo)的關(guān)系
width = right-leftheight = bottom - top
3、Android新增參數(shù)
x、y:View左上角坐標(biāo)
translationX、translationY:相對(duì)于父容器的偏移量(有g(shù)et/set方法),正數(shù)往右,負(fù)數(shù)往左
注意:View在平移過(guò)程中,原始位置不會(huì)改變。
// 換算關(guān)系x = left + translationXy = top + translationY
從API21開(kāi)始增加了z(垂直屏幕方向)和elevation(浮起來(lái)的高度,3D)
4、示例
// 轉(zhuǎn)換為dpLog.e(TAG, "width:" + (getRight() - getLeft()));Log.e(TAG, "寬度(dp):" + Utils.px2dip(context, (getRight() - getLeft())));Log.e(TAG, "height:" + (getBottom() - getTop()));Log.e(TAG, "高度(dp):" + Utils.px2dip(context, (getBottom() - getTop())));

5、dp與px(像素)相互轉(zhuǎn)換代碼
// dp轉(zhuǎn)為pxpublic static int dp2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f);}// px轉(zhuǎn)為dppublic static int px2dp(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f);}三、MotionEvent
1、手指觸摸屏幕后產(chǎn)生的事件,典型事件如下: