当前位置: 首页 > news >正文

仿华为车机UI--图标从Workspace拖动到Hotseat同时保留图标在原来位置

基于Android13 Launcher3,原生系统如果把图标从Workspace拖动到Hotseat里则Workspace就没有了,需求是执行拖拽动作后,图标同时保留在原位置。

实现效果如下:

99fdd6f2bacc40e586ebec33272195eb.gif

实现思路:

1.如果在workspace中拖动,则保留原来“改变图标位置”的功能

2.如果拖拽到Hotseat,则添加到Hotseat的同时也在原来位置复制一个一样的View 

3.每次改变都要存到数据库以保存当前状态

思路非常简单,但是要找适当的位置添加适当的代码不简单。需要读懂原生代码。

分析了源代码后,发现应该参考Workspace.java的onDrop与onDropExternal代码来实现。

step1: 读懂代码后添加注释(中文为添加的注释)和添加onDropToHotseat()的调用

@Overridepublic void onDrop(final DragObject d, DragOptions options) {mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter);CellLayout dropTargetLayout = mDropToLayout;Log.d("drop","onDrop!");// We want the point to be mapped to the dragTarget.if (dropTargetLayout != null) {mapPointFromDropLayout(dropTargetLayout, mDragViewVisualCenter);}boolean droppedOnOriginalCell = false;boolean snappedToNewPage = false;boolean resizeOnDrop = false;Runnable onCompleteRunnable = null;if (d.dragSource != this || mDragInfo == null) {//从别的地方(AllApp等)拖到worksapce的 startfinal int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],(int) mDragViewVisualCenter[1] };onDropExternal(touchXY, dropTargetLayout, d);Log.d("drop","onDropExternal!");//从别的地方(AllApp等)拖到worksapce的 end} else {//从workspace拖到workspace startfinal View cell = mDragInfo.cell;boolean droppedOnOriginalCellDuringTransition = false;if (dropTargetLayout != null && !d.cancelled) {//有地方可放且没有取消拖动 start// Move internallyboolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);Log.d("drop","hasMovedIntoHotseat :"+hasMovedIntoHotseat);int container = hasMovedIntoHotseat ?LauncherSettings.Favorites.CONTAINER_HOTSEAT :LauncherSettings.Favorites.CONTAINER_DESKTOP;int screenId = (mTargetCell[0] < 0) ?mDragInfo.screenId : getIdForScreen(dropTargetLayout);int spanX = mDragInfo != null ? mDragInfo.spanX : 1;int spanY = mDragInfo != null ? mDragInfo.spanY : 1;// First we find the cell nearest to point at which the item is// dropped, without any consideration to whether there is an item there.mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);float distance = dropTargetLayout.getDistanceFromWorkspaceCellVisualCenter(mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);// If the item being dropped is a shortcut and the nearest drop// cell also contains a shortcut, then create a folder with the two shortcuts.if (createUserFolderIfNecessary(cell, container,dropTargetLayout, mTargetCell, distance, false, d)|| addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,distance, d, false)) {mLauncher.getStateManager().goToState(NORMAL, SPRING_LOADED_EXIT_DELAY);return;}// Aside from the special case where we're dropping a shortcut onto a shortcut,// we need to find the nearest cell location that is vacantItemInfo item = d.dragInfo;int minSpanX = item.spanX;int minSpanY = item.spanY;if (item.minSpanX > 0 && item.minSpanY > 0) {minSpanX = item.minSpanX;minSpanY = item.minSpanY;}droppedOnOriginalCell = item.screenId == screenId && item.container == container&& item.cellX == mTargetCell[0] && item.cellY == mTargetCell[1];droppedOnOriginalCellDuringTransition = droppedOnOriginalCell && mIsSwitchingState;// When quickly moving an item, a user may accidentally rearrange their// workspace. So instead we move the icon back safely to its original position.boolean returnToOriginalCellToPreventShuffling = !isFinishedSwitchingState()&& !droppedOnOriginalCellDuringTransition && !dropTargetLayout.isRegionVacant(mTargetCell[0], mTargetCell[1], spanX, spanY);int[] resultSpan = new int[2];if (returnToOriginalCellToPreventShuffling) {mTargetCell[0] = mTargetCell[1] = -1;} else {//让目的地Layout重新布局一下顺序,腾出drop的位置mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],(int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);}boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;// if the widget resizes on dropif (foundCell && (cell instanceof AppWidgetHostView) &&(resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {resizeOnDrop = true;item.spanX = resultSpan[0];item.spanY = resultSpan[1];AppWidgetHostView awhv = (AppWidgetHostView) cell;WidgetSizes.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],resultSpan[1]);}if (foundCell) {//目的地有空出位置 startint targetScreenIndex = getPageIndexForScreenId(screenId);int snapScreen = getLeftmostVisiblePageForIndex(targetScreenIndex);// On large screen devices two pages can be shown at the same time, and snap// isn't needed if the source and target screens appear at the same timeif (snapScreen != mCurrentPage && !hasMovedIntoHotseat) {snapToPage(snapScreen);snappedToNewPage = true;}final ItemInfo info = (ItemInfo) cell.getTag();/*这一段实现把cell从原来的父View中remove掉,添加到目的layout里去 start*/if (hasMovedLayouts) {// Reparent the view  这段非常关键,重新安排父View startLog.d("drop","drop to different layout!!");//表示放在了不同的layout里CellLayout parentCell = getParentCellLayoutForView(cell);if (parentCell != null) {parentCell.removeView(cell);//如果注释这句,就会报错,说明view不能有两个parent} else if (mDragInfo.cell instanceof LauncherAppWidgetHostView) {d.dragView.detachContentView(/* reattachToPreviousParent= */ false);} else if (FeatureFlags.IS_STUDIO_BUILD) {throw new NullPointerException("mDragInfo.cell has null parent");}addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],info.spanX, info.spanY);//假如我们在此调用getParentCellLayoutForView(cell);得到的parentCell就是目的layout了// Reparent the view  这段非常关键,重新安排父View end//added by Kevin.Ye for create keep dragObject when dropped to Hotseatif(hasMovedIntoHotseat)onDropToHotseat(d);//end}/*这一段实现把cell从原来的父View中remove掉,添加到目的layout里去 end*/// update the item's position after drop/*把目的地位置,作为这个cell的位置 start*/CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();lp.cellX = lp.tmpCellX = mTargetCell[0];lp.cellY = lp.tmpCellY = mTargetCell[1];lp.cellHSpan = item.spanX;lp.cellVSpan = item.spanY;lp.isLockedToGrid = true;/*把目的地位置,作为这个cell的位置 end*/if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&cell instanceof LauncherAppWidgetHostView) {//这段处理的是widgetfinal CellLayout cellLayout = dropTargetLayout;// We post this call so that the widget has a chance to be placed// in its final locationfinal LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE&& !options.isAccessibleDrag) {onCompleteRunnable = () -> {if (!isPageInTransition()) {AppWidgetResizeFrame.showForWidget(hostView, cellLayout);}};}}//更新到数据库里去mLauncher.getModelWriter().modifyItemInDatabase(info, container, screenId,lp.cellX, lp.cellY, item.spanX, item.spanY);} else {//没有找到位置drop startif (!returnToOriginalCellToPreventShuffling) {onNoCellFound(dropTargetLayout, d.dragInfo, d.logInstanceId);}if (mDragInfo.cell instanceof LauncherAppWidgetHostView) {d.dragView.detachContentView(/* reattachToPreviousParent= */ true);}// If we can't find a drop location, we return the item to its original positionCellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();mTargetCell[0] = lp.cellX;mTargetCell[1] = lp.cellY;CellLayout layout = (CellLayout) cell.getParent().getParent();layout.markCellsAsOccupiedForView(cell);}//没有找到位置 end} else {//处理取消drag start// When drag is cancelled, reattach content view back to its original parent.if (mDragInfo.cell instanceof LauncherAppWidgetHostView) {d.dragView.detachContentView(/* reattachToPreviousParent= */ true);}//处理取消drag end}final CellLayout parent = (CellLayout) cell.getParent().getParent();if (d.dragView.hasDrawn()) {//拖动View已经绘图 statif (droppedOnOriginalCellDuringTransition) {//过渡的过程中拖到原来的位置 start// Animate the item to its original position, while simultaneously exiting// spring-loaded mode so the page meets the icon where it was picked up.final RunnableList callbackList = new RunnableList();final Runnable onCompleteCallback = onCompleteRunnable;mLauncher.getDragController().animateDragViewToOriginalPosition(/* onComplete= */ callbackList::executeAllAndDestroy, cell,SPRING_LOADED.getTransitionDuration(mLauncher, true /* isToState */));mLauncher.getStateManager().goToState(NORMAL, /* delay= */ 0,onCompleteCallback == null? null: forSuccessCallback(() -> callbackList.add(onCompleteCallback)));mLauncher.getDropTargetBar().onDragEnd();parent.onDropChild(cell);return;}//过渡的过程中拖到原来的位置 endfinal ItemInfo info = (ItemInfo) cell.getTag();boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET|| info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;if (isWidget) {//桌面小组件drop到新位置int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :ANIMATE_INTO_POSITION_AND_DISAPPEAR;animateWidgetDrop(info, parent, d.dragView, null, animationType, cell, false);} else {//图标动画移动到新位置,但如果没有drop到目的地,则会回到原来的位置int duration = snappedToNewPage ? ADJACENT_SCREEN_DROP_DURATION : -1;mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,this);}} else {d.deferDragViewCleanupPostAnimation = false;cell.setVisibility(VISIBLE);}parent.onDropChild(cell);mLauncher.getStateManager().goToState(NORMAL, SPRING_LOADED_EXIT_DELAY,onCompleteRunnable == null ? null : forSuccessCallback(onCompleteRunnable));mStatsLogManager.logger().withItemInfo(d.dragInfo).withInstanceId(d.logInstanceId).log(LauncherEvent.LAUNCHER_ITEM_DROP_COMPLETED);}if (d.stateAnnouncer != null && !droppedOnOriginalCell) {d.stateAnnouncer.completeAction(R.string.item_moved);}}

step2:同样在Workspace.java中添加增加的接口 onDropToHotseat(DragObject d)

 

/** Added by Kevin.Ye* when a shortcut was dropped to Hotseat,we create a new one in original position* */private void onDropToHotseat(DragObject d){ItemInfo info = d.dragInfo;WorkspaceItemInfo newItemInfo = null;View view;switch (info.itemType) {case ITEM_TYPE_APPLICATION:case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:case LauncherSettings.Favorites.ITEM_TYPE_SEARCH_ACTION:if (info instanceof WorkspaceItemFactory) {// Came from all apps -- make a copynewItemInfo = ((WorkspaceItemFactory) info).makeWorkspaceItem(mLauncher);//d.dragInfo = info;}if (info instanceof WorkspaceItemInfo) {// Came from all apps prediction row -- make a copynewItemInfo = new WorkspaceItemInfo((WorkspaceItemInfo) info);//d.dragInfo = info;}view = mLauncher.createShortcut((WorkspaceItemInfo) info);break;case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:view = FolderIcon.inflateFolderAndIcon(R.layout.folder_icon, mLauncher, (ViewGroup) getChildAt(0),(FolderInfo) info);break;default:throw new IllegalStateException("Unknown item type: " + info.itemType);}//final ContentResolver cr = getContext().getContentResolver();//newItemInfo.id = LauncherSettings.Settings.call(cr, LauncherSettings.Settings.METHOD_NEW_ITEM_ID).getInt(LauncherSettings.Settings.EXTRA_VALUE);if(newItemInfo == null)return;newItemInfo.id = ItemInfo.NO_ID;//this is very important,otherwise it won't be add new shortcut in database marked by Kevin.YeLog.d("drop","info.id:"+info.id+" newItemInfo.id:"+newItemInfo.id);// Add the item to DB before adding to screen ensures that the container and other// values of the info is properly updated.Log.d("drop","new shortcut container:"+newItemInfo.container+" screenId:"+newItemInfo.screenId+" cellX:"+newItemInfo.cellX+" cellY:"+newItemInfo.cellY);//info.id = ItemInfo.NO_ID;//it is very important as we need to add new one to database not movemLauncher.getModelWriter().addOrMoveItemInDatabase(newItemInfo, newItemInfo.container, newItemInfo.screenId, newItemInfo.cellX, newItemInfo.cellY);addInScreen(view, newItemInfo.container, newItemInfo.screenId, newItemInfo.cellX, newItemInfo.cellY,newItemInfo.spanX, newItemInfo.spanY);}

 

 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 从监控到智能:EasyCVR视频汇聚平台助力加油站安全监管升级转型
  • 黑神话:游戏的诞生
  • 桥接模式bridge
  • leetcode :746使用最小花费爬楼梯
  • 微软云技术深度解析与实战案例
  • 算法打卡——田忌赛马问题
  • (pycharm)安装python库函数Matplotlib步骤
  • 微服务架构设计模式简要介绍
  • 经验笔记:Spring Boot项目结构
  • Nacos注册中心与OpenFeign远程调用
  • PHP轻量级高性能HTTP服务框架 - webman
  • 【MATLAB】运算符及其优先级
  • sportbugs报告路径在linux和windows中的配置差异
  • 郑州建站网页手机版
  • 深度评测热门翻译工具,携手你的翻译得力助手
  • 《网管员必读——网络组建》(第2版)电子课件下载
  • 07.Android之多媒体问题
  • CSS进阶篇--用CSS开启硬件加速来提高网站性能
  • gcc介绍及安装
  • golang中接口赋值与方法集
  • JAVA之继承和多态
  • Laravel核心解读--Facades
  • React组件设计模式(一)
  • 包装类对象
  • 反思总结然后整装待发
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 聊聊flink的TableFactory
  • 漂亮刷新控件-iOS
  • 思否第一天
  • 小程序button引导用户授权
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • 如何用纯 CSS 创作一个货车 loader
  • ​【数据结构与算法】冒泡排序:简单易懂的排序算法解析
  • #include<初见C语言之指针(5)>
  • (C11) 泛型表达式
  • (附源码)计算机毕业设计ssm本地美食推荐平台
  • (算法)硬币问题
  • (转)C#开发微信门户及应用(1)--开始使用微信接口
  • (转)setTimeout 和 setInterval 的区别
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • ****三次握手和四次挥手
  • .md即markdown文件的基本常用编写语法
  • .NET MAUI Sqlite程序应用-数据库配置(一)
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .net 无限分类
  • .NET项目中存在多个web.config文件时的加载顺序
  • ::before和::after 常见的用法
  • @Transactional注解下,循环取序列的值,但得到的值都相同的问题
  • [ 渗透工具篇 ] 一篇文章让你掌握神奇的shuize -- 信息收集自动化工具
  • [Angular] 笔记 9:list/detail 页面以及@Output
  • [BUUCTF 2018]Online Tool
  • [C++] 默认构造函数、参数化构造函数、拷贝构造函数、移动构造函数及其使用案例
  • [C++]类和对象【上篇】
  • [CSS] 点击事件触发的动画
  • [Django 0-1] Core.Email 模块