EditText是如何实现长按弹出复制粘贴等ContextMenu的源码解析

2024-02-28 09:18

本文主要是介绍EditText是如何实现长按弹出复制粘贴等ContextMenu的源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在做一些关于EditText编辑功能的需求,遇到了很多的问题,比如EditText在RecyclerView中会出现内容错乱、RecyclerView复用EditText后长按无法弹出复制、粘贴、全选ContextMenu等一些问题,在网上也没有搜到比较好的解决方法,于是就想研究一下这方面的源码,希望能帮到有需要的同学,少走一些弯路。 
网上看到的关于EditText的ContextMenu的问题,大部分是如何屏蔽长按后不弹,如何自定义ContextMenu的需求,本篇文章介绍Android系统是如何实现长按EditText弹出ContextMenu的,如果原理都明白了,那问题还不迎刃而解嘛,废话不多说,先看一个效果图: 

非常常见的功能,要研究这个功能的实现该从哪入手呢,我说一下我的思路:从EditText的长按事件开始,翻看EditText的源码,发现内容很少,并没有事件处理方法,于是找到了父View(TextView), TextView中有一个方法叫performLongClick,没错,就是它:

@Overridepublic boolean performLongClick() {boolean handled = false;if (mEditor != null) {mEditor.mIsBeingLongClicked = true;}//执行父view的performLongClickif (super.performLongClick()) {handled = true;}//执行mEditor的performLongClickif (mEditor != null) {handled |= mEditor.performLongClick(handled);mEditor.mIsBeingLongClicked = false;}if (handled) {performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);if (mEditor != null) mEditor.mDiscardNextActionUp = true;}return handled;}



我们发现调用了super.performLongClick(),然后再到View中去看:

private boolean performLongClickInternal(float x, float y) {sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);boolean handled = false;final ListenerInfo li = mListenerInfo;if (li != null && li.mOnLongClickListener != null) {handled = li.mOnLongClickListener.onLongClick(View.this);}if (!handled) {final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);handled = isAnchored ? showContextMenu(x, y) : showContextMenu();}if (handled) {performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);}return handled;}


大家看这一句handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 感觉就要接近真相了,赶紧点进去:

public boolean showContextMenu(float x, float y) {return getParent().showContextMenuForChild(this, x, y);
}


这里面调的是父View的showContextMenuForChild方法,不同的页面父View都不同,一般都是LinearLayout、RelativeLayout,但他们没有重写这个方法,都用的ViewGroup的showContextMenuForChild:

@Overridepublic boolean showContextMenuForChild(View originalView, float x, float y) {try {mGroupFlags |= FLAG_SHOW_CONTEXT_MENU_WITH_COORDS;if (showContextMenuForChild(originalView)) {return true;}} finally {mGroupFlags &= ~FLAG_SHOW_CONTEXT_MENU_WITH_COORDS;}return mParent != null && mParent.showContextMenuForChild(originalView, x, y);}

debug会发现这个方法会一直向上找父View,直到DecorView。DecorView中实际调用了showContextMenuForChildInternal方法:

private boolean showContextMenuForChildInternal(View originalView,float x, float y) {//.....final MenuHelper helper;final boolean isPopup = !Float.isNaN(x) && !Float.isNaN(y);//弹出ContextMenuif (isPopup) {helper = mWindow.mContextMenu.showPopup(getContext(), originalView, x, y);} else {helper = mWindow.mContextMenu.showDialog(originalView, originalView.getWindowToken());}if (helper != null) {// If it's a dialog, the callback needs to handle showing// sub-menus. Either way, the callback is required for propagating// selection to Context.onContextMenuItemSelected().callback.setShowDialogForSubmenu(!isPopup);helper.setPresenterCallback(callback);}mWindow.mContextMenuHelper = helper;return helper != null;}

最关键的一句话helper = mWindow.mContextMenu.showPopup(getContext(), originalView, x, y); 
看到这里本以为真相大白了,遗憾的是debug看这句话返回的helper为null,也就是并没有执行预期的复制、粘贴menu的显示,从showPopup这个方法里面可以看出,这个方法要做的事情就是我们View里面或者是activity里面弹出的ContextMenu,比如,微信的聊天列表,长按弹出的popupWindow就是通过这个方法实现的,这方面的问题百度有很多文章。 
现在线索突然断了,好烦躁,需要静下心来好好思考一下,既然这条路走不通,那肯定有别的途径,还记得前边performLongClick()方法吗?handled |= mEditor.performLongClick(handled); 看到没有,想必就是它了,瞬间精神了许多:

public boolean performLongClick(boolean handled) {// .....省略了无关代码// Start a new selectionif (!handled) {handled = selectCurrentWordAndStartDrag();}return handled;}

看到selectCurrentWordAndStartDrag()这个方法心里就放心了,从字面上能看出是选中当前文字然后开始拖拽。

    /*** If the TextView allows text selection, selects the current word when no existing selection* was available and starts a drag.** @return true if the drag was started.*/private boolean selectCurrentWordAndStartDrag() {//......if (!checkField()) {return false;}//如果mTextView没有选中,那么选中当前文字if (!mTextView.hasSelection() && !selectCurrentWord()) {// No selection and cannot select a word.return false;}stopTextActionModeWithPreservingSelection();getSelectionController().enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD);return true;}

这个方法的注释意思是如果当前TextView允许选中,那么选中当前文字然后开启拖拽效果,selectCurrentWord()方法中关键的一句是Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 可以看出这个地方就是选中当前文字的实现。enterDrag呢?getSelectionController()得到的是SelectionModifierCursorController,这个类从字面上看是选中、修改光标的控制器,

public void enterDrag(int dragAcceleratorMode) {// Just need to init the handles / hide insertion cursor.show();mDragAcceleratorMode = dragAcceleratorMode;// Start location of selection.mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,mLastDownPositionY);mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);// Don't show the handles until user has lifted finger.hide();// ......}

我们看到show()这个方法,很有可能就是显示menu的实现:

 public void show() {if (mTextView.isInBatchEditMode()) {return;}initDrawables();initHandles();}

里面有两个方法,分别看一下:

        private void initDrawables() {//获取选中效果左边的Drawableif (mSelectHandleLeft == null) {mSelectHandleLeft = mTextView.getContext().getDrawable(mTextView.mTextSelectHandleLeftRes);}//获取选中效果右边的Drawableif (mSelectHandleRight == null) {mSelectHandleRight = mTextView.getContext().getDrawable(mTextView.mTextSelectHandleRightRes);}}private void initHandles() {// Lazy object creation has to be done before updatePosition() is called.//将选中效果左右两边的Drawable以SelectionHandleView的形式创建出来if (mStartHandle == null) {mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,com.android.internal.R.id.selection_start_handle,HANDLE_TYPE_SELECTION_START);}if (mEndHandle == null) {mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,com.android.internal.R.id.selection_end_handle,HANDLE_TYPE_SELECTION_END);}//显示两边的DrawablemStartHandle.show();mEndHandle.show();hideInsertionPointCursorController();}

原来这个方法是显示选中文字的两边光标效果的,并没有看到我们预期的结果,烦躁啊,但通过这个方法我们可以看到,如果我们想改变这个光标的话,只需要修改mTextView.mTextSelectHandleLeftRes和mTextView.mTextSelectHandleRightRes就行了,这两个属性想必在TextView的xml里面可以直接设置,也算是有一点点收获吧,至少现在文字已经选中了。 
又经过了很长时间的debug,发现这个menu并没有在performLongClick()方法里实现,而是在onTouchEvent()方法中,当事件为ACTION_UP的时候。

@Overridepublic boolean onTouchEvent(MotionEvent event) {final int action = event.getActionMasked();if (mEditor != null) {mEditor.onTouchEvent(event);if (mEditor.mSelectionModifierCursorController != null &&mEditor.mSelectionModifierCursorController.isDragAcceleratorActive()) {return true;}}//........}

又是mEditor ,看来这个类真的很重要啊,进入onTouchEvent方法

void onTouchEvent(MotionEvent event) {//......if (hasSelectionController()) {getSelectionController().onTouchEvent(event);}//......}

关键的只有这一句,getSelectionController()我们上边已经看到过了,返回的是SelectionModifierCursorController,然后我们看看里面的onTouchEvent方法:

public void onTouchEvent(MotionEvent event) {//......switch (event.getActionMasked()) {//......case MotionEvent.ACTION_UP:if (!isDragAcceleratorActive()) {break;}updateSelection(event);// No longer dragging to select text, let the parent intercept events.mTextView.getParent().requestDisallowInterceptTouchEvent(false);// No longer the first dragging motion, reset.resetDragAcceleratorState();//如果mTextView有选中,那么启动选中actionModeif (mTextView.hasSelection()) {startSelectionActionMode();}break;}}

直接进入MotionEvent.ACTION_UP事件,mTextView.hasSelection()想必肯定是true,以为前面的performLongClick()分析,已经处于选中状态了,赶紧看看这个方法吧:

 boolean startSelectionActionMode() {boolean selectionStarted = startSelectionActionModeInternal();if (selectionStarted) {getSelectionController().show();}mRestartActionModeOnNextRefresh = false;return selectionStarted;}

实际上调用的是startSelectionActionModeInternal()方法,真相已经渐渐浮出水面了,

private boolean startSelectionActionModeInternal() {//......ActionMode.Callback actionModeCallback =new TextActionModeCallback(true /* hasSelection */);mTextActionMode = mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING);//......return selectionStarted;}

关键的地方到了,这里实例化了一个TextActionModeCallback对象,我们看看这个类的实现:

    /*** An ActionMode Callback class that is used to provide actions while in text insertion or* selection mode.** The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace* actions, depending on which of these this TextView supports and the current selection.*/private class TextActionModeCallback extends ActionMode.Callback2 {//......@Overridepublic boolean onCreateActionMode(ActionMode mode, Menu menu) {mode.setTitle(null);mode.setSubtitle(null);mode.setTitleOptionalHint(true);populateMenuWithItems(menu);Callback customCallback = getCustomCallback();if (customCallback != null) {if (!customCallback.onCreateActionMode(mode, menu)) {// The custom mode can choose to cancel the action mode, dismiss selection.Selection.setSelection((Spannable) mTextView.getText(),mTextView.getSelectionEnd());return false;}}if (mTextView.canProcessText()) {mProcessTextIntentActionsHandler.onInitializeMenu(menu);}if (menu.hasVisibleItems() || mode.getCustomView() != null) {if (mHasSelection && !mTextView.hasTransientState()) {mTextView.setHasTransientState(true);}return true;} else {return false;}}}


看一下这个类的注释,这是一个用来提供文本的插入、选中等操作的回调,默认的回调提供了全选、剪切、复制、粘贴、分享和替换,真的就是它了, 
这里需要提一嘴的是Callback customCallback = getCustomCallback();这一句表示开发者可以自己实现menu的创建,通过TextView的setCustomSelectionActionModeCallback()方法设置的,如果大家有这个需求的话可以在这个地方尝试(我没试过)。 
默认的menu是通过populateMenuWithItems(menu);这句话实现的:

        private void populateMenuWithItems(Menu menu) {if (mTextView.canCut()) {menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,com.android.internal.R.string.cut).setAlphabeticShortcut('x').setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);}if (mTextView.canCopy()) {menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,com.android.internal.R.string.copy).setAlphabeticShortcut('c').setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);}if (mTextView.canPaste()) {menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,com.android.internal.R.string.paste).setAlphabeticShortcut('v').setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);}if (mTextView.canShare()) {menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,com.android.internal.R.string.share).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);}updateSelectAllItem(menu);updateReplaceItem(menu);}

现在实现menu的地方已经找到了,那么在什么时候会调用onCreateActionMode呢?什么时候回显示呢?我们继续看看前边的startSelectionActionModeInternal()方法,下边一句是mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING);这个方法有两个参数,第一个参数就是我们刚刚分析的TextActionModeCallback 回调,是menu的实现,第二个参数是ActionMode.TYPE_FLOATING,应该是在显示menu的时候用到的,floating嘛,对不对,继续跟进:

public ActionMode startActionMode(ActionMode.Callback callback, int type) {ViewParent parent = getParent();if (parent == null) return null;try {return parent.startActionModeForChild(this, callback, type);} catch (AbstractMethodError ame) {// Older implementations of custom views might not implement this.return parent.startActionModeForChild(this, callback);}}

这里面会一直调用parent.startActionModeForChild,一直到DecorView,最终会调用到DecorView的startActionMode()方法:

private ActionMode startActionMode(View originatingView, ActionMode.Callback callback, int type) {//将callback包装到wrappedCallback ActionMode.Callback2 wrappedCallback = new ActionModeCallback2Wrapper(callback);ActionMode mode = null;//......if (mode != null) {if (mode.getType() == ActionMode.TYPE_PRIMARY) {//......} else {//这里会创建一个FloatingActionModemode = createActionMode(type, wrappedCallback, originatingView);//调用TextActionModeCallback 类的onCreateActionMode方法创建menuif (mode != null && wrappedCallback.onCreateActionMode(mode, mode.getMenu())) {//处理ActionModesetHandledActionMode(mode);} else {mode = null;}}
//......return mode;}

这里面我们看到了创建menu的调用代码,想必setHandledActionMode(mode);这个方法会将它show出来:

private void setHandledActionMode(ActionMode mode) {if (mode.getType() == ActionMode.TYPE_PRIMARY) {setHandledPrimaryActionMode(mode);} else if (mode.getType() == ActionMode.TYPE_FLOATING) {setHandledFloatingActionMode(mode);}}

这里看到了前面提到的ActionMode.TYPE_FLOATING的作用了,继续看:

private void setHandledFloatingActionMode(ActionMode mode) {mFloatingActionMode = mode;//创建FloatingToolbarmFloatingToolbar = new FloatingToolbar(mContext, mWindow);((FloatingActionMode) mFloatingActionMode).setFloatingToolbar(mFloatingToolbar);//显示FloatingToolbarmFloatingActionMode.invalidate();  // Will show the floating toolbar if necessary.mFloatingActionModeOriginatingView.getViewTreeObserver().addOnPreDrawListener(mFloatingToolbarPreDrawListener);}

到这里就终于结束了,menu最终以FloatingToolbar的形式显示出来

总结一下
1、EditText(或者说TextView)长按选中的效果是在Editor.performLongClick(handled)中实现的,这个方法会让当前文本处于选中状态,并显示选中的左右Drawable

2、长按弹出的复制、全选、粘贴等menu的显示过程:首先是Editor内部类SelectionModifierCursorController在onTouchEvent处理MotionEvent.ACTION_UP事件,然后调用startSelectionActionModeInternal()方法,并创建了TextActionModeCallback用来初始化menuItem,然后通过TextView的startActionMode一直往上找,最终由DecorView以FloatingToolbar的形式展现出来。

3、如果我们想自定义menu有哪些item,可以通过TextView的setCustomSelectionActionModeCallback实现,可以参照TextActionModeCallback。

这篇关于EditText是如何实现长按弹出复制粘贴等ContextMenu的源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/755055

相关文章

深入解析Java NIO在高并发场景下的性能优化实践指南

《深入解析JavaNIO在高并发场景下的性能优化实践指南》随着互联网业务不断演进,对高并发、低延时网络服务的需求日益增长,本文将深入解析JavaNIO在高并发场景下的性能优化方法,希望对大家有所帮助... 目录简介一、技术背景与应用场景二、核心原理深入分析2.1 Selector多路复用2.2 Buffer

Qt中实现多线程导出数据功能的四种方式小结

《Qt中实现多线程导出数据功能的四种方式小结》在以往的项目开发中,在很多地方用到了多线程,本文将记录下在Qt开发中用到的多线程技术实现方法,以导出指定范围的数字到txt文件为例,展示多线程不同的实现方... 目录前言导出文件的示例工具类QThreadQObject的moveToThread方法实现多线程QC

Go语言使用sync.Mutex实现资源加锁

《Go语言使用sync.Mutex实现资源加锁》数据共享是一把双刃剑,Go语言为我们提供了sync.Mutex,一种最基础也是最常用的加锁方式,用于保证在任意时刻只有一个goroutine能访问共享... 目录一、什么是 Mutex二、为什么需要加锁三、实战案例:并发安全的计数器1. 未加锁示例(存在竞态)

基于Redisson实现分布式系统下的接口限流

《基于Redisson实现分布式系统下的接口限流》在高并发场景下,接口限流是保障系统稳定性的重要手段,本文将介绍利用Redisson结合Redis实现分布式环境下的接口限流,具有一定的参考价值,感兴趣... 目录分布式限流的核心挑战基于 Redisson 的分布式限流设计思路实现步骤引入依赖定义限流注解实现

SpringBoot实现虚拟线程的方案

《SpringBoot实现虚拟线程的方案》Java19引入虚拟线程,本文就来介绍一下SpringBoot实现虚拟线程的方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录什么是虚拟线程虚拟线程和普通线程的区别SpringBoot使用虚拟线程配置@Async性能对比H

基于Python实现进阶版PDF合并/拆分工具

《基于Python实现进阶版PDF合并/拆分工具》在数字化时代,PDF文件已成为日常工作和学习中不可或缺的一部分,本文将详细介绍一款简单易用的PDF工具,帮助用户轻松完成PDF文件的合并与拆分操作... 目录工具概述环境准备界面说明合并PDF文件拆分PDF文件高级技巧常见问题完整源代码总结在数字化时代,PD

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南

《SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南》本文将基于开源项目springboot-easyexcel-batch进行解析与扩展,手把手教大家如何在SpringBo... 目录项目结构概览核心依赖百万级导出实战场景核心代码效果百万级导入实战场景监听器和Service(核心

C# async await 异步编程实现机制详解

《C#asyncawait异步编程实现机制详解》async/await是C#5.0引入的语法糖,它基于**状态机(StateMachine)**模式实现,将异步方法转换为编译器生成的状态机类,本... 目录一、async/await 异步编程实现机制1.1 核心概念1.2 编译器转换过程1.3 关键组件解析

基于Python Playwright进行前端性能测试的脚本实现

《基于PythonPlaywright进行前端性能测试的脚本实现》在当今Web应用开发中,性能优化是提升用户体验的关键因素之一,本文将介绍如何使用Playwright构建一个自动化性能测试工具,希望... 目录引言工具概述整体架构核心实现解析1. 浏览器初始化2. 性能数据收集3. 资源分析4. 关键性能指