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

devtools/2024/9/20 7:05:23/ 标签: 华为, ui, android, Launcher3, java

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

实现效果如下:

99fdd6f2bacc40e586ebec33272195eb.gif

实现思路:

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

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

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

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

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

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

java">@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)

 

java">/** 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);}

 

 


http://www.ppmy.cn/devtools/109029.html

相关文章

项目日志——日志等级类和日志消息类的设计、实现、测试

文章目录 日志等级类设计实现测试 日志消息类设计实现 日志等级类 设计 日志等级一共分7个等级 UNKNOW 0OFF 关闭所有日志输出DEBUG 调试等级INFO 提示等级WARN 警告等级ERROR 错误等级FATAL 致命等级OFF 关闭所有日志的输出 每一个项目都会设置一个默认输出等级&#xff…

前端项目开发之prettier安装和使用

前端项目开发之安装prettier和使用 Prettier 是一个流行的代码格式化工具&#xff0c;可以帮助你保持代码风格的一致性。以下是如何在 Visual Studio Code (VS Code) 中安装和使用 Prettier 的步骤&#xff1a; 安装 Prettier 通过 VS Code 扩展市场安装&#xff1a; 打开 V…

使用AI赋能进行软件测试-文心一言

1.AI赋能的作用 提高速度和效率缺陷预测与分析 2.AI互动指令格式--文心一言 角色、指示、上下文例子、输入、输出 a 直接问AI 针对以下需求&#xff0c;设计测试用例。 需求&#xff1a; 1、账号密码登录系统验证账号和密码的正确性。 验证通过,用户登录成功,进入个人中心;验…

pytorch tensor.expand函数介绍

在 PyTorch 中&#xff0c;tensor.expand()是一个用于扩展张量维度的函数。 一、函数作用 它允许你在不复制数据的情况下&#xff0c;将张量的形状扩展到指定的维度大小。这对于需要在特定维度上重复数据的操作非常有用&#xff0c;例如在进行广播操作时调整张量的形状。 二…

Web3社交新经济,与 SOEX 实现无缝交易的高级安全性

出于充分的理由&#xff0c;安全性是交易中至关重要的考虑因素。每个人都应该确保自己的资金在交易时是安全的。由于 &#xff33;&#xff2f;&#xff25;&#xff38; 充当您与交易所的最佳连接&#xff0c;因此必须强调的是&#xff0c;该系统不会引发任何安全问题。 &a…

com.baomidou.mybatisplus.annotation.DbType 无法引入

com.baomidou.mybatisplus.annotation.DbType 无法引入爆红 解决 解决 ❤️ 3.4.1 是mybatis-plus版本&#xff0c;根据实际的配置→版本一致 <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-annotation</artifactId>&…

[动态规划] 删除并获得点数

给你一个整数数组 nums &#xff0c;你可以对它进行一些操作。 每次操作中&#xff0c;选择任意一个 nums[i] &#xff0c;删除它并获得 nums[i] 的点数。之后&#xff0c;你必须删除 所有 等于 nums[i] - 1 和 nums[i] 1 的元素。 开始你拥有 0 个点数。返回你能通过这些操…

国内短剧系统怎么搭建以及都需要那些资质?

聊到国内短剧&#xff0c;相信大家都不陌生&#xff0c;在各大短视频平台可谓是火的一批&#xff0c;您或许有想加入进来的想法&#xff0c;或是已经有规划还未实现的&#xff0c;请停下脚步&#xff0c;耐心看完该文章&#xff0c;相信一定会对你有所帮助的。本文介绍短剧平台…

做饭时用什么样的白酒能更好衬托食物的鲜味?

在做饭的时候&#xff0c;白酒扮演着举足轻重的角色&#xff0c;其核心功能在于祛除食材不良风味并显著提升菜肴的香醇层次。挑选适宜的白酒时&#xff0c;需细致考量其种类与酒精浓度&#xff0c;尽量与食材的风味和谐共生&#xff0c;而非相互抵触。以下是酱酒亮哥yutengtrad…

LeetCode HOT100系列题解之最大正方形(6/100)

题目&#xff1a;最大正方形. - 力扣&#xff08;LeetCode&#xff09; 题解&#xff1a; 第一种方法&#xff1a;前缀和二分答案&#xff08;暴力优化&#xff09;我感觉比官方给的暴力好一点 时间复杂度&#xff1a; 暴力优化1&#xff1a;通过前缀和减少判断1出现得次数…

SpringBoot教程(十五) | SpringBoot集成RabbitMq(消息丢失、消息重复、消息顺序、消息顺序)

SpringBoot教程&#xff08;十五&#xff09; | SpringBoot集成RabbitMq&#xff08;消息丢失、消息重复、消息顺序、消息顺序&#xff09; RabbitMQ常见问题解决方案问题一&#xff1a;消息丢失的解决方案&#xff08;1&#xff09;生成者丢失消息丢失的情景解决方案1&#xf…

Elasticsearch之原理详解

简介 ES是使用 Java 编写的一种开源搜索引擎&#xff0c;它在内部使用 Lucene 做索引与搜索&#xff0c;通过对 Lucene 的封装&#xff0c;隐藏了 Lucene 的复杂性&#xff0c;取而代之的提供一套简单一致的 RESTful API 然而&#xff0c;Elasticsearch 不仅仅是 Lucene&#…

【ES备份和还原索引数据】

文章目录 备份&#xff08;Snapshot&#xff09;还原&#xff08;Restore&#xff09;注意事项示例 在 Elasticsearch 中&#xff0c;备份和还原索引数据通常通过快照&#xff08;Snapshot&#xff09;和恢复&#xff08;Restore&#xff09;机制来实现。以下是详细的操作步骤&…

【RabbitMQ】核心概念

界⾯上的导航栏共分6部分, 这6部分分别是什么意思呢, 我们先看看RabbitMQ的工作流程 1. Producer和Consumer Producer:生产者,是RabbitMQ Server的客户端,向RabbitMQ发送消息 Consumer: 消费者,也是RabbitMQ Server的客户端,从RabbitMQ接收消息 Broker:其实就是RabbitMQSer…

策略规划:在MySQL中实现数据恢复的全面指南

数据恢复是数据库管理中至关重要的一环&#xff0c;它确保在发生数据丢失或损坏的情况下&#xff0c;能够迅速且准确地恢复数据。在MySQL中&#xff0c;实现有效的数据恢复策略规划需要综合考虑备份策略、备份类型、存储管理、故障转移机制以及恢复流程。本文将深入探讨如何在M…

springcloud-GateWay

Spring Cloud Gateway 是 Spring Cloud 微服务架构中的一个重要组件&#xff0c;用于提供 API 网关功能。作为 API 网关&#xff0c;Spring Cloud Gateway 充当客户端和后端服务之间的代理&#xff0c;负责请求路由、过滤、安全认证、负载均衡等功能。在分布式系统中&#xff0…

2024数学建模国赛B题代码

B题已经完成模型代码&#xff01;详情查看文末名片 问题1&#xff1a;可以考虑使用统计学中的“样本量估算”方法&#xff0c;使用二项分布或正态近似来决定最少的样本量&#xff0c;并通过假设检验&#xff08;如单侧检验&#xff09;在95%和90%置信度下进行判断。 import n…

漫谈设计模式 [6]:适配器模式

引导性开场 菜鸟&#xff1a;老鸟&#xff0c;我最近在项目中遇到一个问题&#xff0c;我们的系统需要集成一个新的第三方库&#xff0c;但这个库的接口和我们现有的代码完全不兼容。我该怎么办&#xff1f; 老鸟&#xff1a;这是个常见的问题&#xff0c;很多开发者都会遇到…

浙大数据结构:03-树3 Tree Traversals Again

这道题也不算难&#xff0c;我依然采用map来进行处理 &#xff0c;代码依旧较短 机翻 1、条件准备 我这里采用数组模拟栈&#xff0c;tt指向栈顶&#xff1b; map的键存结点值&#xff0c;后面数对存左右子树的结点值 head存头节点的值 #include<iostream> #include…

【自动驾驶】控制算法(八)横向控制Ⅰ | 算法与流程

写在前面&#xff1a; &#x1f31f; 欢迎光临 清流君 的博客小天地&#xff0c;这里是我分享技术与心得的温馨角落。&#x1f4dd; 个人主页&#xff1a;清流君_CSDN博客&#xff0c;期待与您一同探索 移动机器人 领域的无限可能。 &#x1f50d; 本文系 清流君 原创之作&…