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

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

实现效果如下:

实现思路:

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);}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/52707.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Scratch教学案例-《三顾茅庐》:让编程学习如同故事般引人入胜

三顾茅庐-小虎鲸Scratch资源站 在编程的世界里&#xff0c;我们常常寻找那种既能激发创意&#xff0c;又能提升技能的学习方式。今天&#xff0c;小虎鲸Scratch资源站为您带来了一款独特的教学作品——《三顾茅庐》。这是一部将经典故事与编程教学巧妙结合的Scratch项目&#x…

在docker中安装skywalking + es

ES的版本和官网 es版本&#xff1a; Past Releases of Elastic Stack Software | Elastic es版本logstash版本JDK版本对应关系 支持一览表 | Elastic skywalking的版本说明和官网 Advanced deployment | Apache SkyWalking skywalking和es的对应关系&#xff0c;在网页的…

读书笔记:《深入理解Java虚拟机》(4)

垃圾收集器与内存分配策略 一、对象已死&#xff1f; 堆中几乎放着所有的对象实例&#xff0c;对堆垃圾回收前的第一步就是要判断哪些对象已经死亡&#xff08;即不能再被任何途径使用的对象&#xff09;。 引用计数法 给对象中添加一个引用计数器&#xff1a; 每当有一个…

day03-面向对象-内部类泛型常用API

一、内部类 内部类是类中的五大成分之一&#xff08;成员变量、方法、构造器、代码块、内部类&#xff09; 如果一个类定义在另一个类的内部&#xff0c;这个类就是内部类。 场景&#xff1a;当一个类的内部&#xff0c;包含了一个完整的事物&#xff0c;且这个事物没有必要单…

bitmap(位图)的使用

零存零取&#xff0c;整存零取&#xff0c;整存整取, 零存整取 bitmap介绍 位图不是真正的数据类型&#xff0c;它是定义在字符串类型中,一个字符串类型的值最多能存储512M字节的内容, 位上限&#xff1a;2^(9(512)10(1024)10(1024)3(8b1B))2^32b 语句操作&#xff1a; s…

[报错] nvcc -V 找不到

报错&#xff1a; nvcc : 无法将“nvcc”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写&#xff0c;ObjectNotFound: (nvcc:String) [], CommandNotFoundExceptionFullyQualifiedErrorId : CommandNotFoundException 找不到 nvcc -V&#xff0c;试过…

鸿蒙(API 12 Beta5版)【通过文本生成码图】

基本概念 码图生成能力支持将字符串转换为自定义格式的码图。 场景介绍 码图生成能力支持将字符串转换为自定义格式的码图&#xff0c;包含条形码、二维码生成。 可以将字符串转成联系人码图&#xff0c;手机克隆码图&#xff0c;例如将"HUAWEI"字符串生成码图使…

深度学习系列71:表格检测和识别

1. pdf处理 如果是可编辑的pdf格式&#xff0c;那么可以直接用pdfplumber进行处理&#xff1a; import pdfplumber import pandas as pdwith pdfplumber.open("中新科技&#xff1a;2015年年度报告摘要.PDF") as pdf:page pdf.pages[1] # 第一页的信息text pag…

【开端】基于nginx部署的具有网关的web日志分析

一、绪论 基于nginx部署的具有网关的web日志分析&#xff0c;我们可以分析的日志有nginx的access.log &#xff0c;网关的日志和应用的日志 二、日志分析 1、nginx日志 参数 说明 示例 $remote_addr 客户端地址 172.17.0.1 $remote_user 客户端用户名称 -- $time_lo…

Datawhale AI夏令营

一、物体检测算法 物体检测算法主要分为两类&#xff1a;One-Stage&#xff08;一阶段&#xff09;和Two-Stage&#xff08;两阶段&#xff09;模型。 二、One-Stage目标检测算法 定义&#xff1a;One-Stage目标检测算法是一种直接在图像上进行目标检测的方法&#xff0c;无…

数字化转型升级探索(二)

在数字化转型升级的探索中&#xff0c;我们计划通过整合前沿技术如人工智能、物联网和大数据&#xff0c;全面改造传统业务流程&#xff0c;打造智能化、数据驱动的业务架构&#xff0c;实现从数据采集、处理到分析的全链条数字化&#xff0c;以提升决策效率、优化运营管理&…

C++和QT

什么是QT Qt 是一个跨平台的 C图形用户界面应用程序框架。 它为应用程序开发者提供建立艺术级图形界面所需的所有功能。 它是完全面向对象的&#xff0c;很容易扩展&#xff0c;并且允许真正的组件编程。 QT的优点 跨平台&#xff0c;几乎支持所有的平台 接口简单&#x…

pandas操作Excel文件

pandas操作Excel文件 一、前言二、指定读取的工作表与header设置2.1指定工作表2.2header设置 三、读取Excel数据3.1iloc读取数据3.2read_excel读取数据3.3loc读取数据 四、DataFrame数据筛选4.1根据列标签对整列进行筛选4.2使用iloc对区域进行筛选4.3自定义筛选 五、DataFrame类…

【GPT】Coze使用开放平台接口-【6】Dify 也来一遍

前面讲了 coze 的相关用法&#xff0c;这边想着用 Dify 也来一遍&#xff0c;刚开始的时候接触的是 Dify&#xff0c;后面才是 coze。Dify 和 coze 的侧重点不同&#xff0c;我个人是更倾向用 Dify 构建工作流就可以了&#xff0c;coze 还是相对全能。 本节用 Dify 也会创建插…

Linux文件IO缓存

一、缓冲区大小对 I/O 系统调用性能的影响 总之&#xff0c;如果与文件发生大量的数据传输&#xff0c;通过采用大块空间缓冲数据&#xff0c;以及执行更少的 系统调用&#xff0c;可以极大地提高 I / O 性能 二、stdio 库的缓冲 当操作磁盘文件时&#xff0c;缓冲大块数据以…

ArcGIS Pro技术应用

GIS是利用电子计算机及其外部设备&#xff0c;采集、存储、分析和描述整个或部分地球表面与空间信息系统。简单地讲&#xff0c;它是在一定的地域内&#xff0c;将地理空间信息和 一些与该地域地理信息相关的属性信息结合起来&#xff0c;达到对地理和属性信息的综合管理。GIS的…

Hreflang 和 SEO:新手完整指南

每天&#xff0c;数以百万计的法国用户访问像 Amazon.com 这样的全球网站。虽然 Amazon.com 的官方页面是英文的&#xff0c;但用户仍然可以看到法语的文本和产品描述。这是因为亚马逊的全球网站有针对法国的本地化版本&#xff0c;确保所有法国用户都可以自动看到法语的网站内…

五种多目标优化算法(NSGA3、MOPSO、MOGWO、NGSA2、SPEA2)性能对比,包含47个多目标测试函数,6种评价指标,MATLAB代码

一、五种多目标算法及六种评价指标简介 多目标灰狼优化算法&#xff08;MOGWO&#xff09;&#xff1a; MOGWO是由Mirjalili等人在2016年提出的&#xff0c;基于灰狼优化算法&#xff08;GWO&#xff09;的多目标版本。它引入了存档机制和改进的头狼选择方式&#xff0c;以处理…

uniapp(微信小程序如何使用单选框、复选框)

一、先看效果 二、数据结构 说明&#xff1a;selected用来记录每次用户选择的值&#xff0c;当是单选的时候属性中的selected属性需要设置成字符串&#xff0c;当是复选框的时候&#xff0c;此时选择的是数组&#xff0c;selected属性应设置为数组。type用来区分当前是单选还是…

【C++ Qt day3】

2、设计一个Per类&#xff0c;类中包含私有成员:姓名、年龄、指针成员身高、体重&#xff0c;再设计一个Stu类&#xff0c;类中包含私有成员:成绩、Per类对象p1&#xff0c;设计这两个类的构造函数、析构函数和拷贝构造函数。