当前位置:网站首页>Android Culture Series (11), kotlin Static Method
Android Culture Series (11), kotlin Static Method
2022-01-15 02:28:04 【Mb61c1dbbb44788】
android:layout_height=“70dp”
android:text=“Draggable”
android:gravity=“center”
android:textColor=“#fff”
android:background=“#6495ED”
/>
</com.blog.a.drag.DragViewGroup>
C'est très facile?,J'ai téléchargé les châtaignes du blog. gitHubAllez.,Si vous êtes intéressé, téléchargez - le..
Code source
Cet article analyse principalement,Lorsque l'événement tactile commence à se terminer,processTouchEventProcessus de traitement:
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
MotionEvent.ACTION_DOWN
Lorsque les doigts entrent en contact avec l'écran,Ça va déclencherACTION_DOWN Événements,AdoptionMotionEventNous pouvons voir ce qui s'est passé x, y Coordonnées,Attention icigetX/getYLes coordonnées sont relatives au courantviewOui..PointerEst le concept de contact,UnMotionEventPeut contenir plus d'unPointerInformations sur les contacts tactiles,Et chaquePointerTous les contacts auront leur propreidEtindex.Regardez en bas.
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
final int pointerId = ev.getPointerId(0);
final View toCapture = findTopChildUnder((int) x, (int) y);
saveInitialMotion(x, y, pointerId);
tryCaptureViewForDrag(toCapture, pointerId);
// mTrackingEdgesPar défaut0,Peut passerViewDragHelper#setEdgeTrackingEnabled(int)
// Pour mettre en place,Utilisé pour contrôler le rappel du bord tactileonEdgeTouched
final int edgesTouched = mInitialEdgesTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
break;
}
Ici.findTopChildUnderLa méthode est utilisée pour obtenir le courantx, yOù se trouve le point de coordonnéesview,La valeur par défaut est supérieure,Bien sûr, on peut aussicallback#getOrderedChildIndex(int) Interface à partir de la définitionviewOrdre de traversée,Voir le code ci - dessous:
public View findTopChildUnder(int x, int y) {
final int childCount = mParentView.getChildCount();
for (int i = childCount - 1; i >= 0; i–) {
final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
if (x >= child.getLeft() && x < child.getRight()
&& y >= child.getTop() && y < child.getBottom()) {
return child;
}
}
return null;
}
Ici.saveInitialMotionLa méthode est utilisée pour enregistrer les informations de position tactile actuelles,Parmi euxgetEdgesTouchedLa méthode est utilisée pour jugerx, yEst situé iciviewGroupAu - delà du bord,Retour à enregistrerresultRésultats.todo:L'article suivant va écrire sur les opérateurs de bits,C'est intéressant..
private void saveInitialMotion(float x, float y, int pointerId) {
ensureMotionHistorySizeForId(pointerId);
mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
mInitialEdgesTouched[pointerId] = getEdgesTouched((int) x, (int) y);
mPointersDown |= 1 << pointerId;
}
Parmi euxtryCaptureViewForDragDans la méthode,mCapturedViewEst la vue actuellement touchéeview,Retour direct si identique,Sinon, c'est fait.mCallback#tryCaptureView(View, int)Jugement,Ça vous dit quelque chose?,Nous pouvons réécrire ce rappel pour contrôlertoCaptureC'estviewPeut être capturé,C'est - à - dire si l'opération peut être traînée.
boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
if (toCapture == mCapturedView && mActivePointerId == pointerId) {
// Already done!
return true;
}
if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
mActivePointerId = pointerId;
captureChildView(toCapture, pointerId);
return true;
}
return false;
}
Ici.captureChildViewMéthode utilisée pour sauvegarder l'information,Et définir l'état de traînée.Peut remarquer,Il y a une autre capture ici.viewOui Nonchild viewJugement.
public void captureChildView(@NonNull View childView, int activePointerId) {
if (childView.getParent() != mParentView) {
throw new IllegalArgumentException("captureChildView: parameter must be a descendant "
- “of the ViewDragHelper’s tracked parent view (” + mParentView + “)”);
}
mCapturedView = childView;
mActivePointerId = activePointerId;
mCallback.onViewCaptured(childView, activePointerId);
setDragState(STATE_DRAGGING);
}
MotionEvent.ACTION_POINTER_DOWN
Lorsque l'utilisateur touche l'écran avec un autre doigt,Ça va déclencherACTION_POINTER_DOWN Événements,Et au - dessusACTION_DOWN Similaire,Il n'y a plus de détails..Parce queViewDragHelperUne seule vue à la fois,C'est pour ça qu'il faut d'abord juger de l'état.,Si la vue n'a pas été saisie et traînée,Alors la logique etACTION_POINTER_DOWND'accord.,Au contraire,Détermine si le contact est dans la vue courante,Si les conditions sont remplies,Mise à jourPointer,C'est important ici.,Incarné dansuiEn effet,,Un doigt.view,L'autre doigt peut encore faire glisser ceciview.
case MotionEvent.ACTION_POINTER_DOWN: {
final int pointerId = ev.getPointerId(actionIndex);
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
saveInitialMotion(x, y, pointerId);
// A ViewDragHelper can only manipulate one view at a time.
if (mDragState == STATE_IDLE) {
// If we’re idle we can do anything! Treat it like a normal down event.
final View toCapture = findTopChildUnder((int) x, (int) y);
tryCaptureViewForDrag(toCapture, pointerId);
final int edgesTouched = mInitialEdgesTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
} else if (isCapturedViewUnder((int) x, (int) y)) {
tryCaptureViewForDrag(mCapturedView, pointerId);
}
break;
}
MotionEvent.ACTION_MOVE
Lorsque les doigts se déplacent sur l'écran,Si la vue est traînée,Le courant sera jugé en premiermActivePointerIdOui Non,Sauter le courant si invalidemoveÉvénements.Puis obtenir le courantx, yEt calculé par rapport à la dernière foisx, yDistance de déplacement.Déclenché aprèsdragToFaites glisser la logique,Enregistrer l'emplacement pour enregistrer cette fois.Approche de basedragToL'analyse est présentée ci - dessous.:
case MotionEvent.ACTION_MOVE: {
if (mDragState == STATE_DRAGGING) {
// If pointer is invalid then skip the ACTION_MOVE.
if (!isValidPointerForActionMove(mActivePointerId)) break;
final int index = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(index);
final float y = ev.getY(index);
final int idx = (int) (x - mLastMotionX[mActivePointerId]);
final int idy = (int) (y - mLastMotionY[mActivePointerId]);
dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy);
saveLastMotion(ev);
} else {
// Check to see if any pointer is now over a draggable view.
…
}
break;
}
InmoveEn cours,AdoptiondragTo Méthode pour passer à la cible x, y Et les décalages horizontaux et verticaux ,Et à traverscallback Rappel pour informer le développeur ,Le développeur peut réécrireclampViewPositionHorizontalAvecclampViewPositionVertical Ces deux méthodes de rappel ,De la définitionclampedX,clampedYPosition cible.Utilisation ultérieureoffsetLeftAndRightEtoffsetTopAndBottom Les méthodes sont décalées dans les directions respectives (clampedX - oldLeft)Et(clampedY - oldTo)Pixels de.Déclencheur finalonViewPositionChanged Rappel pour changement de position .
private void dragTo(int left, int top, int dx, int dy) {
int clampedX = left;
int clampedY = top;
final int oldLeft = mCapturedView.getLeft();
final int oldTop = mCapturedView.getTop();
if (dx != 0) {
clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
ViewCompat.offsetLeftAndRight(mCapturedView, clampedX - oldLeft);
}
if (dy != 0) {
clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
ViewCompat.offsetTopAndBottom(mCapturedView, clampedY - oldTop);
}
if (dx != 0 || dy != 0) {
final int clampedDx = clampedX - oldLeft;
final int clampedDy = clampedY - oldTop;
mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY,
clampedDx, clampedDy);
}
}
Si le doigt se déplace sur l'écran , Et si la vue n'était pas en état de traînée ? Je vais d'abord vérifier s'il y a d'autres PointerOui Non. Déclenche ensuite un rappel de traînée de bord , Le contrôle de l'état est ensuite effectué , Cela devrait être fait pour éviter que l'état ne soit pas traîné par -> L'état de traînée ,Par exemple::smoothSlideViewTo La méthode a ce pouvoir .SimDragState Dans un état non traîné , Vous récupérerez x,y Vue de l'emplacement view Et Réinitialiser l'état de traînée , Cette logique est liée à downMême logique..
case MotionEvent.ACTION_MOVE: {
if (mDragState == STATE_DRAGGING) {
// If pointer is invalid then skip the ACTION_MOVE.
…
} else {
// Check to see if any pointer is now over a draggable view.
final int pointerCount = ev.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
final int pointerId = ev.getPointerId(i);
// If pointer is invalid then skip the ACTION_MOVE.
if (!isValidPointerForActionMove(pointerId)) continue;
final float x = ev.getX(i);
final float y = ev.getY(i);
final float dx = x - mInitialMotionX[pointerId];
final float dy = y - mInitialMotionY[pointerId];
reportNewEdgeDrags(dx, dy, pointerId);
if (mDragState == STATE_DRAGGING) {
// Callback might have started an edge drag.
break;
}
final View toCapture = findTopChildUnder((int) x, (int) y);
À la fin
Beaucoup de gens qui viennent d'entrer en contact avec l'industrie ou qui rencontrent des goulets d'étranglement,Il y a toujours des problèmes,Comme apprendre pendant un certain temps et se sentir désorienté,Je ne sais pas par où commencer à apprendre,J'ai rassemblé des informations à ce sujet,Vous pouvez partager gratuitement ce dont vous avez besoin
Mon 【Github】Partagez quelques informations surAndroidConnaissance de l'avancement,Partagez également les dernières questions d'entrevue~
Si vous maîtrisez bienGitHubPoints de connaissance énumérés dans,Je crois que cela augmentera considérablement vos chances de réussir les deux premières séries d'entrevues techniques!Tout ceci est pour votre information,Apprendre les uns des autres.
①「AndroidAnalyse complète du vrai problème de l'entrevue」PDFVersion HD complète+②「AndroidInterview Knowledge System」Apprendre la carte mentale comprimer le paquet——————Peut être dans mon 【Github】Lire le téléchargement,J'ai fini par me sentir utile、Un ami dans le besoin peut commander un coup de pouce
版权声明
本文为[Mb61c1dbbb44788]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/01/202201150224018059.html
边栏推荐
- The world is always hostile to good people.
- Re regular matching findall (. +?) Match any content that conforms to a certain format (regular matching catch bullet screen)
- Android中的羊角符,面試看這個就够了
- 數據分析八大模型:OGSM模型
- La corne d'agneau d'Android, c'est assez pour l'interview
- Huit modèles d'analyse des données: modèle ogsm
- Exemple d'application de linq
- Utilisez S7. Net communication library
- Écrire La Bibliothèque de communication Modbus TCP
- Lire le profil INI
猜你喜欢
-
Utilisez S7. Net read Siemens 1500plc
-
Halcon joint C # Programming Experiment
-
Utiliser nmodbus4 pour lire les données à la fois RTU et TCP
-
Tiktok Data Analysis options Platform - tichoo Data
-
MySQL review: create tables, MySQL data types, primary key constraints, primary key
-
Linear Algebra: matrix review
-
Review of Linear Algebra: determinant
-
The digital RMB cross-border payment test has been continuously promoted, and mainland residents can also shop in Hong Kong in the future
-
Thesis classification and writing basis
-
YC Framework version update: v1.0 zero point two
随机推荐
- Analyse des données tichoo
- Tiktok data analysis platform
- Partage de l'industrie | tichoo Data to attend 2022 Overseas Short video Industry Summit
- [ticoo Information Station] tiktok and Cross - Border E - commerce Weekly Report
- Options d'analyse des données ticoo {infostation}
- Partage de l'industrie | Lu Shidong, PDG de tichoo Data Outlook Global Video e - commerce future Blueprint
- [ticoo Information Station]
- Noël Black Five
- YC Framework version update: v1.0 zero point two
- Lucene分词器
- Gbase 8A slow SQL optimization case
- 微服务系列--聊聊微服务治理中的一些感悟
- 线程池的经典应用场景
- [web security from getting started to giving up] 07_ Insecure file download and upload vulnerability
- 如何落地一款重试组件
- 一起聊聊设计原则
- 大话Redis系列--深入探讨多路复用(上)
- 大话Redis系列--实战案例总结(下)
- 大话Redis系列--实战案例总结(上)
- JVM系列 -- G1与低延迟垃圾收集器
- JVM系列 -- 深入剖析垃圾收集器
- JVM系列--内存回收
- JVM系列--对象内存分配技术分析
- JVM系列--虚拟机的内存管理
- 系统性能瓶颈排查技术总结
- 使用redis的scan指令详解
- 实战--分布式id发号器
- 分布式事务之超详细的Seata实践记录
- TCP time_wait
- IP数据报头部
- 最大基环内向树
- MySQL实战45讲 学习笔记(七)
- MySQL实战45讲 学习笔记(六)
- Android从零开始搭建MVVM架构(1)(1),kotlin匿名函数
- Android事件分发机制五:面试官你坐啊,安卓上机面试题
- There will be two different stages between the breakthrough of science and technology and its real transformation into an inclusive technology
- [leetcode] force deduction 200 Number of islands
- HashShuffleManager
- Altium Designer
- Android construit l'architecture mvvm à partir de zéro (1) (1), fonction anonyme kotlin