最近一段时间都没有更新文章,趁工作之余,更新一篇。

今天介绍一个很常见效果也最容易被忽略的弹出框:ActionMode。主要是ActionMode使用和自己使用过程中遇到的一些问题,相对还是比较简单的。

1、ActionMode的基本使用

2、使用ActionMode遇到的一些问题

1、ActionMode的基本使用

主要分两步:

1、实现ActionMode.Callback接口

2、调用startActionMode或者startSupportActionMode

1、实现ActionMode.Callback接口

对于ActionMode.Callback,我们需要实现其四个方法:

new ActionMode.Callback() {
            //Called when action mode is first created.
            // The menu supplied will be used to generate action buttons for the action mode
            //当ActionMode第一次被创建的时候调用
            //可在这里初始化menu
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            menu.findItem(R.id.action_edit).setIcon(R.drawable.ic_launcher);
                return true;//返回true表示action mode会被创建  false if entering this mode should be aborted.
            }
            //
            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }
            //当ActionMode被点击时调用
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                 switch (item.getItemId()) {
                    case R.id.action_edit:
                            rename();
                        return true;
                    }
                return false;
            }
            //Called when an action mode is about to be exited and destroyed.
            //当ActionMode退出销毁时调用
            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        };

2、调用startActionMode或者startSupportActionMode开启弹出框

ActionMode mActionMode = = startSupportActionMode(actionModeCallback)

可以为ActionMode设置属性:mActionMode.setTitlemActionMode.setSubtitle

2、使用ActionMode遇到的坑

坑一:ActionMode把Toolbar压下去了

在theme加入配置:

<item name="windowActionModeOverlay">true</item>

<item name="android:windowActionModeOverlay">true</item>

坑二:修改ActionMode背景

在theme加入配置:

<item name="android:actionModeBackground">@color/colorPrimary</item>

<item name="actionModeBackground">@color/colorPrimary</item>

坑三:屏蔽掉WebView的ActionMode用自己的选择复制

通过js与webView互调来实现文本复制

stackoverflow链接:http://stackoverflow.com/questions/6058843/android-how-to-select-texts-from-webview

public class MyCustomWebView extends WebView{
    private Context context;
    // override all other constructor to avoid crash
    public MyCustomWebView(Context context) {
        super(context);
        this.context = context;
        WebSettings webviewSettings = getSettings();
        webviewSettings.setJavaScriptEnabled(true);
        // add JavaScript interface for copy
        addJavascriptInterface(new WebAppInterface(context), "JSInterface");
    }

    // setting custom action bar
    private ActionMode mActionMode;
    private ActionMode.Callback mSelectActionModeCallback;
    private GestureDetector mDetector;

    // this will over ride the default action bar on long press
    @Override
    public ActionMode startActionMode(ActionMode.Callback callback) {
        ViewParent parent = getParent();
        if (parent == null) {
            return null;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            String name = callback.getClass().toString();
            if (name.contains("SelectActionModeCallback")) {
                mSelectActionModeCallback = callback;
                mDetector = new GestureDetector(context,
                        new CustomGestureListener());
            }
        }
        CustomActionModeCallback mActionModeCallback = new CustomActionModeCallback();
        return parent.startActionModeForChild(this, mActionModeCallback);
    }

    private class CustomActionModeCallback implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mActionMode = mode;
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

            switch (item.getItemId()) {
                case R.id.copy:
                    getSelectedData();
                    mode.finish();
                    return true;
                case R.id.share:
                    mode.finish();
                    return true;
                default:
                    mode.finish();
                    return false;
            }
        }
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                clearFocus();
            }else{
                if (mSelectActionModeCallback != null) {
                    mSelectActionModeCallback.onDestroyActionMode(mode);
                }
                mActionMode = null;
            }
        }
    }
    private void getSelectedData(){

        String js= "(function getSelectedText() {"+
                "var txt;"+
                "if (window.getSelection) {"+
                "txt = window.getSelection().toString();"+
                "} else if (window.document.getSelection) {"+
                "txt = window.document.getSelection().toString();"+
                "} else if (window.document.selection) {"+
                "txt = window.document.selection.createRange().text;"+
                "}"+
                "JSInterface.getText(txt);"+
                "})()";
        // calling the js function
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript("javascript:"+js, null);
        }else{
            loadUrl("javascript:"+js);
        }
    }

    private class CustomGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (mActionMode != null) {
                mActionMode.finish();
                return true;
            }
            return false;
        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Send the event to our gesture detector
        // If it is implemented, there will be a return value
        if(mDetector !=null)
            mDetector.onTouchEvent(event);
        // If the detected gesture is unimplemented, send it to the superclass
        return super.onTouchEvent(event);
    }
    public class WebAppInterface {
        Context mContext;
        WebAppInterface(Context c) {
            mContext = c;
        }
        @JavascriptInterface
        public void getText(String text) {
            // put selected text into clipdata
            ClipboardManager clipboard = (ClipboardManager)
                    mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("simple text",text);
            clipboard.setPrimaryClip(clip);
            // gives the toast for selected text
            Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
        }
    }
}

menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/copy"
        android:icon="@android:drawable/ic_dialog_email"
        app:showAsAction="always"
        android:title="copy">
    </item>
    <item
        android:id="@+id/share"
        android:icon="@android:drawable/ic_dialog_alert"
        app:showAsAction="always"
        android:title="share">
    </item>
    </menu>

坑四:ActionMode显示时状态栏闪动,表现为变黑之后恢复正常

onDestroyActionMode方法加入如下代码:

    @Override
    public final void onDestroyActionMode(ActionMode mode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            new Handler().postDelayed(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    try {
                        mActivity.getWindow().setStatusBarColor(mActivity.getResources().getColor(android.R.color.transparent));
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }, 400);
        }
        //TODO ...

    }

[Android]聊聊ActionMode的更多相关文章

  1. Android新的menu实现——ActionMode

    Android的menu有多种实现方式,以前写过一篇Android中五种常用的menu(菜单),这里介绍一种新的menu实现方式:ActionMode.ActionMode是Android 3.0以后 ...

  2. (转)Android新的menu实现——ActionMode

    Android的menu有多种实现方式,以前写过一篇Android中五种常用的menu(菜单),这里介绍一种新的menu实现方式:ActionMode.ActionMode是Android 3.0以后 ...

  3. Android — 长按ListView 利用上下文菜单(ActionMode) 进行批量事件处理

    好久没写博客拉``````` 近期最终略微闲一点了``````` 无聊拿手机清理短信.发现批量事件的处理还是挺管用的`````` 那么自己也来山寨一记看看效果吧````` 闲话少说,首先,我们来看下手 ...

  4. Android Contextual Menus之二:contextual action mode

    Android Contextual Menus之二:contextual action mode 接上文:Android Contextual Menus之一:floating context me ...

  5. [zt] Android中使用List列表

    原文地址:http://www.vogella.com/tutorials/AndroidListView/article.html 1. Android and Lists 1.1. Using l ...

  6. Android ActionBar 一步一步分析 (转)

    原文摘自:http://blog.csdn.net/android2me/article/details/8874846 1.Action Bar 介绍 我们能在应用中看见的actionbar一般就是 ...

  7. ActionMode 就记这么一点,不能更多了

    话说程序猿都是段子手,看到有的程序猿写文章,前面都会先写一个段子,我这么有幽默感的段子手,也决定效仿一下. "段子." 写完段子,下面开始进入正题. 今天要说的 ActionMod ...

  8. 【凯子哥带你夯实应用层】使用ActionMode实现有删除动画的多选删除功能

        转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992      ActionMode是3.0之后.官方推荐的一种上下文菜单的实现方式,在之前一直用的是Co ...

  9. Android EditText禁止复制粘贴

    1,自定义EditText package com.example.ui; import android.annotation.SuppressLint; import android.content ...

随机推荐

  1. C#生成MD5码

    /// <summary> /// 获取文件的MD5码 /// </summary> /// <param name="fileName">传入 ...

  2. Unity依赖注入

    一.简介 Unity是一个轻量级的可扩展的依赖注入容器,支持构造函数,属性和方法调用注入.Unity可以处理那些从事基于组件的软件工程的开发人员所面对的问题.构建一个成功应用程序的关键是实现非常松散的 ...

  3. [LeetCode] 24 Game 二十四点游戏

    You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated ...

  4. python 随笔

    python 学习笔记 运算符重载 PYTHON-进阶-魔术方法小结(方法运算符重载) python有着像C++相似的运算符重载,只需要在类中重写__add__.sub 等方法,就可以直接对对象进行 ...

  5. Html5调用电脑摄像头-----火狐浏览器、360浏览器、搜狗浏览器、谷歌浏览器

     <!DOCTYPE html>  <html lang="en">  <head>  <meta charset="UTF-8 ...

  6. nginx方向代理

    nginx 的安装 # yum install nginx 新建配置文件 # vi /etc/nginx/conf.d/resume-xyz-8081.conf 配置 upstream resume ...

  7. ●HDU 6021 MG loves string

    题链: http://acm.hdu.edu.cn/showproblem.php?pid=6021 题解: 题意:对于一个长度为 N的由小写英文字母构成的随机字符串,当它进行一次变换,所有字符 i ...

  8. hdu 5489(LIS最长上升子序列)

    题意:一个含有n个元素的数组,删去k个连续数后,最长上升子序列        /*思路参考GoZy 思路: 4 2 3 [5 7 8] 9 11 ,括号表示要删掉的数, 所以  最长上升子序列  = ...

  9. IPQ4028开启I2C功能

    0 概述 IPQ4028是一款集约式4核心ARM7 SOC芯片,内嵌独立双频WiFi子系统,offload式,支持MU-MIMO,最高支持1.2Gbps.标准的官方Demo方案中,IPQ4019开启了 ...

  10. Java Servlet 笔记3

    Servlet 表单数据 很多情况下,需要传递一些信息,从浏览器到 Web 服务器,最终到后台程序.浏览器使用两种方法可将这些信息传递到 Web 服务器,分别为 GET 方法和 POST 方法. 1. ...