国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android中View位置和觸摸事件詳解

2019-12-12 00:35:44
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

一、簡(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ù)
  • MotionEvent屏幕觸摸事件
  • GestureDetector手勢(shì)檢測(cè)(單擊,雙擊,長(zhǎng)摁,滑動(dòng))

二、View的位置參數(shù)


1、原始位置(不受偏移量影響,單位是像素px)

  • top 左上角縱坐標(biāo) -> getTop();
  • left 左上角橫坐標(biāo) -> getLeft();
  • right 右下角橫坐標(biāo) -> getRight();
  • bottom 右下角縱坐標(biāo) -> getBottom();

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)生的事件,典型事件如下: