1. View樹
- View是所有控件的基類,比如TextView和ImageView都繼承自View。
- ViewGroup繼承自View,同時(shí)也是View的組合缕陕,可以包含多個(gè)View以及ViewGroup,而它包含的ViewGroup又可以包含多個(gè)View和ViewGroup疙挺。
2. 坐標(biāo)系
Android系統(tǒng)有兩種坐標(biāo)系:Android坐標(biāo)系和View坐標(biāo)系扛邑。
2.1 Android坐標(biāo)系
- 在Android中,屏幕左上角的頂點(diǎn)作為Android坐標(biāo)系的原點(diǎn)铐然,這個(gè)原點(diǎn)向右是X軸正方向蔬崩,向下是Y軸正方向恶座。
- 使用getRawX()和getRawY()方法獲得的坐標(biāo)也是Android坐標(biāo)系的坐標(biāo)。
2.2 View坐標(biāo)系
- View獲取自身的寬和高
width = getRight()- getLeft();
height = getBottom() - getTop();
說明:系統(tǒng)為我們提供了獲取View的寬和高的方法沥阳。
public final int getWidth() {
return mRight - mLeft;
}
public final int getHeight() {
return mBottom - mTop;
}
- View自身的坐標(biāo)
通過如下方法可以獲得View到父控件(ViewGroup)的距離跨琳。
- getTop():獲取View自身頂邊到父布局頂邊的距離。
- getLeft():獲取View自身左邊到其父布局左邊的距離桐罕。
- getRight():獲取View自身右邊到其父布局左邊的距離脉让。
- getBottom():獲取View自身底邊到其父布局頂邊的距離。
- MotionEvent提供的方法
View坐標(biāo)系中的圓點(diǎn)就是我們假設(shè)就是我們觸摸的點(diǎn)功炮。
不管是View還是ViewGroup溅潜,最終的點(diǎn)擊事件都會由onTouchEvent(MotionEvent event)方法來處理。
MotionEvent在用戶交互中作用巨大薪伏。其內(nèi)部提供了許多常量滚澜,比如ACTION_DOWN ACTION_UP ACTION_MOVE .此外,MotionEvent也提供了獲取焦點(diǎn)坐標(biāo)的各種方法嫁怀。
- getX:獲取點(diǎn)擊事件距離控件左邊的距離设捐,即視圖坐標(biāo)。
- getY:獲取點(diǎn)擊事件距離控件頂邊的距離眶掌,即視圖坐標(biāo)挡育。
- getRawX:獲取點(diǎn)擊事件距離整個(gè)屏幕左邊的距離巴碗,即絕對坐標(biāo)朴爬。
- getRawY:獲取點(diǎn)擊事件距離整個(gè)屏幕頂邊的距離,即絕對坐標(biāo)橡淆。
3. View的滑動
- View滑動的基本思想:當(dāng)點(diǎn)擊事件傳到View時(shí)召噩,系統(tǒng)記下觸摸點(diǎn)的坐標(biāo),手指移動時(shí)系統(tǒng)記下移動后觸摸的坐標(biāo)并算出偏移量逸爵,并通過偏移量來修改View的坐標(biāo)具滴。
- 實(shí)現(xiàn)View的滑動有6種基本方法:layout() offsetLeftAndRight()和offsetTopAndBottom() LayoutParams 動畫 scrollTo和srcollBy Scroller
3.1 layout()方法
- View繪制的時(shí)候會調(diào)用onLayout方法來設(shè)置顯示的位置,因此我們也可以修改View的left师倔、top构韵、right、bottom這4種屬性來控制View的坐標(biāo)趋艘。
/**
* Created by FuKaiqiang on 2017-11-13.
*/
public class CustomView extends View {
private int lastX;
private int lastY;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//獲取手機(jī)觸摸點(diǎn)的橫坐標(biāo)和縱坐標(biāo)
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//記錄手機(jī)按下的坐標(biāo)
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
//計(jì)算移動的距離
int offsetX = x - lastX;
int offsetY = y - lastY;
//調(diào)用layout方法來重新放置它的位置
layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY);
break;
}
//處理點(diǎn)擊事件返回true
return true;
}
}
<com.best.testview.CustomView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="50dp"
android:background="@android:color/holo_red_light"/>
說明:
- 首先自定義CustomView繼承自View疲恢,在onTouchEvent方法中獲取觸摸點(diǎn)的坐標(biāo)。
- 然后在ACTION_MOVE事件中計(jì)算偏移量瓷胧,再調(diào)用layout方法重新設(shè)置這個(gè)自定義View的位置即可显拳。
- 每次移動時(shí)都會調(diào)用layout方法對屏幕重新布局,從而達(dá)到移動View的效果搓萧。
- 把自定義View引用到布局中即可杂数。
3.2 offsetLeftAndRight與offsetTopAndBottom
- 這兩種方法和layout方法的效果差不多宛畦,將ACTION_MOVE中的代碼可替換成以下代碼:
//計(jì)算移動的距離
int offsetX = x - lastX;
int offsetY = y - lastY;
//對left和right進(jìn)行偏移
offsetLeftAndRight(offsetX);
//對top和bottom進(jìn)行偏移
offsetTopAndBottom(offsetY);
break;
3.3 LayoutParams(改變布局參數(shù))
- LayoutParams保存了一個(gè)View的布局參數(shù),我們可以通過LayoutParams來改變View的布局參數(shù)從而改變View位置的效果揍移,次和,將ACTION_MOVE中的代碼可替換成以下代碼:
//計(jì)算移動的距離
int offsetX = x - lastX;
int offsetY = y - lastY;
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop()+offsetY;
setLayoutParams(layoutParams);
說明:如果父控件是LinearLayout,我們就用LinearLayout.LayoutParams羊精。如果父控件是RelativieLayout斯够,則要使用RelativeLayout.LayoutParams.除了使用布局的LayoutParams外,我們還可以使用ViewGroup.MarginLayoutParams來實(shí)現(xiàn):
//計(jì)算移動的距離
int offsetX = x - lastX;
int offsetY = y - lastY;
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
注意:如果父布局是ConstraintLayout喧锦,測試結(jié)果是ConstraintLayout.LayoutParams無效读规, ViewGroup.MarginLayoutParams無效。
3.4 動畫
- 采用View動畫來移動燃少,在res目錄新建anim文件夾并創(chuàng)建translate.xml,然后用java代碼調(diào)用即可束亏。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromXDelta="0"
android:toXDelta="300">
</translate>
</set>
mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));
說明:我們會發(fā)現(xiàn)方塊向右平移了300像素,然后又回到原來的位置阵具,為了解決這個(gè)問題碍遍,我們在translate.xml中加上fillAfter = "true",方塊平移后就停留在當(dāng)前位置了。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<translate
android:duration="1000"
android:fromXDelta="0"
android:toXDelta="300">
</translate>
</set>
注意:當(dāng)然View動畫并不會改變View的位置參數(shù)阳液,也就是說點(diǎn)擊事件的響應(yīng)還在原始位置怕敬,對系統(tǒng)來說,方塊位置并沒有改變帘皿。Android 3.0出現(xiàn)的屬性動畫就解決了上述問題东跪,代碼如下:
ObjectAnimator.ofFloat(mCustomView, "translationX", 0, 300).setDuration(1000).start();
3.5 scrollTo與scrollBy
- scrollTo(x,y)表示移動到了一個(gè)具體的坐標(biāo)點(diǎn),而scrollBy(dx,dy)則表示移動的增量為dx鹰溜、dy虽填。其中scrollBy最終也是要調(diào)用scrollTo的〔芏看下源碼:
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();
}
}
}
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
注意:scrollTo斋日、scrollBy移動的是View的內(nèi)容,如果再ViewGroup中使用墓陈,則是移動其所有的子View恶守,我們將ACTION_MOVE代碼替換為以下代碼:
((View) getParent()).scrollBy(-offsetX, -offsetY);
說明:可能你會問為何設(shè)置為負(fù)值,是因?yàn)閟crollBy這個(gè)方法移動的是手機(jī)的屏幕而不是View贡必。而上面的其他方法移動的都是View兔港。
3.6 Scroller
- scrollTo/scrollBy方法進(jìn)行滑動時(shí),這個(gè)過程是瞬間完成的赊级。我們可以使用Scroller實(shí)現(xiàn)有過渡效果的滑動押框,不是瞬間完成的,而是在一定的時(shí)間間隔內(nèi)完成的理逊。
- Scroller本身是不能實(shí)現(xiàn)View的滑動的橡伞,它需要與View的computeScroll方法配合才能實(shí)現(xiàn)彈性滑動的效果盒揉。
- 在這里我們實(shí)現(xiàn)CustomView平滑地向右移動,首先我們需要初始化Scroller:
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
- 接下來重寫computeScroll方法兑徘,此方法會在View繪制的時(shí)候在draw方法中被調(diào)用刚盈。我們調(diào)用父類的scrollTo方法并通過Scroller來不斷獲取當(dāng)前的滾動值,每次滑動一小段距離我們就調(diào)用invalidate方法不斷進(jìn)行重繪挂脑,重繪會調(diào)用computeScroll方法藕漱,我們通過不斷地移動一個(gè)小的距離并連貫起來就實(shí)現(xiàn)了平滑移動的效果。
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
}
}
- 我們在CustomView中寫一個(gè)smoothScrollTo方法崭闲,調(diào)用Scroller的startScroll方法肋联,2000ms內(nèi)沿X軸平移delta像素,代碼如下:
public void smoothScrollTo(int destX,int destY){
int scrollX = getScrollX();
int delta = destX - scrollX;
mScroller.startScroll(scrollX,0,delta,0,2000);
invalidate();
}
- 調(diào)用代碼刁俭,設(shè)定CustomView沿著X軸向右平移400像素橄仍。為了看到效果,我們延遲3秒牍戚。向右移動就是負(fù)數(shù)侮繁,向左移動就是正數(shù)。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mCustomView.smoothScrollTo(-300, 0);
}
}, 3000);