如何在我的 Android 应用程序中以编程方式复制文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/238284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:06:12  来源:igfitidea点击:

How to copy text programmatically in my Android app?

androidmenuclipboardmanager

提问by Zach

I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press Menu+Athen Menu+Cto copy the value, but how would I do this programmatically?

我正在构建一个 Android 应用程序,我想复制 EditText 小部件的文本值。用户可以按Menu+AthenMenu+C复制值,但我将如何以编程方式执行此操作?

回答by FlySwat

Use ClipboardManager#setPrimaryClipmethod:

使用ClipboardManager#setPrimaryClip方法:

import android.content.ClipboardManager;

// ...

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);

ClipboardManagerAPI reference

ClipboardManager接口参考

回答by Warpzit

So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:

所以每个人都同意应该如何做,但由于没有人想给出一个完整的解决方案,这里是:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("text to clip");
} else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
    clipboard.setPrimaryClip(clip);
}

I assume you have something like following declared in manifest:

我假设您在清单中声明了以下内容:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />

回答by Viachaslau Tysianchuk

Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API < 11, because the documentation page says "Since: API Level 11".

谷歌搜索将您带到 android.content.ClipboardManager,您可以像我一样决定剪贴板在 API < 11 上不可用,因为文档页面上写着“因为:API 级别 11”。

There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.

实际上有两个类,第二个扩展了第一个类 - android.text.ClipboardManager 和 android.content.ClipboardManager。

android.text.ClipboardManager is existing since API 1, but it works only with text content.

android.text.ClipboardManager 从 API 1 开始就存在,但它只适用于文本内容。

android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level < 11 (Honeycomb).

android.content.ClipboardManager 是使用剪贴板的首选方式,但它在 API 级别 < 11 (Honeycomb) 上不可用。

To get any of them you need the following code:

要获得其中任何一个,您需要以下代码:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

But for API < 11you have to import android.text.ClipboardManagerand for API >= 11android.content.ClipboardManager

但是对于API < 11你必须导入android.text.ClipboardManager并且对于API >= 11android.content.ClipboardManager

回答by ayrina

public void onClick (View v) 
{
    switch (v.getId())
    {
        case R.id.ButtonCopy:
            copyToClipBoard();
            break;
        case R.id.ButtonPaste:
            pasteFromClipBoard();
            break;
        default:
            Log.d(TAG, "OnClick: Unknown View Received!");
            break;
    }
}

// Copy EditCopy text to the ClipBoard
private void copyToClipBoard() 
{
    ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipMan.setPrimaryClip(editCopy.getText());
}

you can try this..

你可以试试这个..

回答by live-love

Here is some code to implement some copy and paste functions from EditText (thanks to Warpzit for version check). You can hook these to your button's onclick event.

这是一些代码,用于从 EditText 实现一些复制和粘贴功能(感谢 Warpzit 进行版本检查)。您可以将它们与按钮的 onclick 事件挂钩。

public void copy(View v) {      
    int startSelection = txtNotes.getSelectionStart();
    int endSelection = txtNotes.getSelectionEnd();      
    if ((txtNotes.getText() != null) && (endSelection > startSelection ))
    {
        String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection);                
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(selectedText);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            android.content.ClipData clip = android.content.ClipData.newPlainText("WordKeeper",selectedText);
            clipboard.setPrimaryClip(clip);
        }
    }
}   

public void paste(View v) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());
        }
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
        if (item.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());
        }
    }
}

回答by Suragch

Android support library update

Android 支持库更新

As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)

从 Android Oreo 开始,支持库仅适用于 API 14。大多数较新的应用程序的最低 API 可能也为 14,因此无需担心其他一些答案中提到的 API 11 问题。很多代码都可以清理。(但如果您仍然支持较低版本,请查看我的编辑历史记录。)

Copy

复制

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", selectedText);
if (clipboard == null || clip == null) return;
clipboard.setPrimaryClip(clip);

Paste

粘贴

I'm adding this code as a bonus, because copy/paste is usually done in pairs.

我添加此代码作为奖励,因为复制/粘贴通常成对完成。

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

Notes

笔记

  • Be sure to import the android.content.ClipboardManagerversion rather than the old android.text.ClipboardManager. Same for ClipData.
  • If you aren't in an activity you can get the service with context.getSystemService().
  • I used a try/catch block for getting the paste text because multiple things can be null. You can check each one if you find that way more readable.
  • 确保导入android.content.ClipboardManager版本而不是旧的android.text.ClipboardManager. 对于ClipData.
  • 如果您不在活动中,则可以通过context.getSystemService().
  • 我使用了一个 try/catch 块来获取粘贴文本,因为多个东西可以是null. 如果您发现这种方式更具可读性,您可以检查每一个。

回答by King of Masses

To enable the standard copy/paste for TextView, U can choose one of the following:

要启用 TextView 的标准复制/粘贴,您可以选择以下选项之一:

Change in layout file: add below property to your TextView

布局文件中的更改:将以下属性添加到您的 TextView

android:textIsSelectable="true"

In your Java class write this line two set the grammatically.

在您的 Java 类中,在语法上写下这一行两行。

myTextView.setTextIsSelectable(true);

myTextView.setTextIsSelectable(true);

And long press on the TextView you can see copy/paste action bar.

长按 TextView 您可以看到复制/粘贴操作栏。

回答by Mor2

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
if (clipboard == null || clip == null)
    return;
clipboard.setPrimaryClip(clip);

And importimport android.content.ClipboardManager;

并导入import android.content.ClipboardManager;

回答by Trinity

@FlySwat already gave the correct answer, I am just sharing the complete answer:

@FlySwat 已经给出了正确答案,我只是分享完整的答案:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

使用 ClipboardManager.setPrimaryClip ( http://developer.android.com/reference/android/content/ClipboardManager.html) 方法:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where labelis a User-visible label for the clip data and textis the actual text in the clip. According to official docs.

其中label是剪辑数据的用户可见标签,是剪辑 text中的实际文本。根据官方文档

It is important to use this import:

使用此导入很重要:

import android.content.ClipboardManager;

回答by Mehul Boghra

Here is my working code

这是我的工作代码

/**
 * Method to code text in clip board
 *
 * @param context context
 * @param text    text what wan to copy in clipboard
 * @param label   label what want to copied
 */
public static void copyCodeInClipBoard(Context context, String text, String label) {
    if (context != null) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        if (clipboard == null || clip == null)
            return;
        clipboard.setPrimaryClip(clip);

    }
}