1. 程式人生 > 其它 >短視訊app開發,介面滑動到底的幾種實現方式

短視訊app開發,介面滑動到底的幾種實現方式

短視訊app開發,介面滑動到底的幾種實現方式

1.1 那麼說明一下 getLegt(),getTop(),getBottom(),getRight();其實就是獲取View自身到其父佈局的距離。

如:getLegt() 就是獲取自身左邊到父佈局左邊的距離;

getTop() 就是獲取自身上邊到父佈局上邊的距離;

1.2 那麼getX(),getY(),getRawX(),getRawY(); 是什麼呢?

假設上圖中View中的那個小圓點是我們點選觸控的位置,無論是ViewGroup還是View我們知道都是由onTouchEvent(MotionEvent event)處理,也就是說MotionEvent在與使用者互動關係極大。

那麼在MotionEvent中提供的獲取焦點座標的方法:

getX() 獲取當前點選事件距離控制元件左邊的位置。(檢視座標) (注意是控制元件左邊的位置也就是自身View)

getY() 獲取當前點選事件距離控制元件頂部位置。 (檢視座標) (注意是控制元件左邊的位置也就是自身View)

getRawX() 獲取點選事件距離螢幕左邊的位置。(絕對座標) (注意是當前螢幕也就是手機邊緣)

getRawY()獲取點選事件距離螢幕頂邊的位置。 (絕對座標) (注意是當前螢幕也就是手機邊緣)

------------------------------------------要注意分清MotionEvent中的座標系和1.1的座標系--------------------------------------------

1.3 View的滑動實現View的滑動也就是學會自定義View的基礎,在開發中我們難免會處理View的滑動,那麼實現View滑動的細想大概都是一致的記錄點選的觸控點手指移動記錄後觸控的座標計算偏移量,並通過偏移量更改View座標實現View的滑動,這邊只講解layout(),offsetTopAndBottom()與offsetLeftAndRight(),LayputParams(), 這幾種方法,對於動畫實現滑動或者Scroller,ScrollTo(),ScrollBy()留到下個章節講不然篇幅有點長。

1.3.1 layout()

View進行繪製的時候會呼叫onLayout()方法來設定View的顯示位置,那麼我們可以通過修改view的,left、top、right、bottom這4種屬性來控制View的座標,首先使用自定義View整合View 重寫onTouchEvent 方法即可。

 @Override
public boolean onTouchEvent(MotionEvent event) {
//獲取手指觸控式螢幕幕的橫座標和縱座標
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()){
//手勢點選
case MotionEvent.ACTION_DOWN:
mX=x;
mY=y;
break;
//手勢滑動
case MotionEvent.ACTION_MOVE:
//計算移動的距離
int flx= x-mX;
int fly= y-mY;
//呼叫layout方法讓View重新計算自己的位置
layout(getLeft()+flx,getTop()+fly,getRight()+flx,getBottom()+fly);
break;
//手勢抬起
case MotionEvent.ACTION_UP:
break;
}
return true;
}

接著在佈局因為我們自定義的View就可以實現滑動

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.example.myapplication.DemoView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/demoview"
android:background="@color/colorPrimary"
android:layout_margin="26dp"/>
</LinearLayout>

如DemoView就是我實現的自定義View重寫了onTouEvent;

1.3.2 offsetTopAndBottom()與offsetLeftAndRight()

@Override
publicbooleanonTouchEvent(MotionEventevent){
//獲取手指觸控式螢幕幕的橫座標和縱座標
intx=(int)event.getX();
inty=(int)event.getY();
switch(event.getAction()){
//手勢點選
caseMotionEvent.ACTION_DOWN:
mX=x;
mY=y;
break;
//手勢滑動
caseMotionEvent.ACTION_MOVE:
//計算移動的距離
intflx=x-mX;
intfly=y-mY;
offsetTopAndBottom(fly);
offsetLeftAndRight(flx);
break;
//手勢抬起
caseMotionEvent.ACTION_UP:
break;
}
returntrue;
}

offsetTopAndBottom()檢視座標圖會發現Bottom的計算是通過縱軸去定義所以我們把Y軸的偏移量給到了offsetTopAndBottomoffsetLeftAndRight 是通過橫軸去計算所以我們給到X 的偏移量給到offsetLeftAndRight

以上就是短視訊app開發,介面滑動到底的幾種實現方式, 更多內容歡迎關注之後的文章