How to use the new Android M feature of “Text Selection” to be offered from outside of your app?

后端 未结 2 1183
小蘑菇
小蘑菇 2020-12-04 22:42

Background

Android M presents a new way to handle selected text (link here), even from outside of your app . Text selection can be handled as such:

2条回答
  •  鱼传尺愫
    2020-12-04 23:35

    This article on Android Developers Blog may be relevant, it describes how Google Translate option can be added to overflow text selection menu.

    Android apps that use Android text selection behavior will already have this feature enabled, so no extra steps need to be taken. Developers who created custom text selection behavior for their apps can easily implement this feature by following the below steps:

    Scan via the PackageManager through all packages that have the PROCESS_TEXT intent filter (for example: com.google.android.apps.translate - if it installed) and add them as MenuItems into TextView selections for your app

    To query the package manager, first build an intent with the action Intent.ACTION_PROCESS_TEXT, then retrieve the supported activities and add an item for each retrieved activity and attach an intent to it to launch the action

    public void onInitializeMenu(Menu menu) {
        // Start with a menu Item order value that is high enough
        // so that your "PROCESS_TEXT" menu items appear after the
        // standard selection menu items like Cut, Copy, Paste.
        int menuItemOrder = 100;
        for (ResolveInfo resolveInfo : getSupportedActivities()) {
            menu.add(Menu.NONE, Menu.NONE,
                    menuItemOrder++,
                    getLabel(resolveInfo))
                .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }
    

提交回复
热议问题