从剪贴板管理器复制/粘贴Android

时间:2013-10-04 09:01:51

标签: android copy-paste clipboardmanager

是否可以发送过去的命令,以便将文本粘贴到当前聚焦的编辑文本中。 情形:

  1. 后台服务侦听通知(已完成)
  2. 收到通知时,需要将文本复制到剪贴板(已完成)
  3. 将文本粘贴到任何当前关注的字段,如果不可能,只需放弃粘贴命令。
  4. 我知道如何使用ClipboardManager复制文字,但我不知道如何粘贴它。

8 个答案:

答案 0 :(得分:25)

您可以使用以下代码复制和粘贴文字:

  • 复制:

    ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("your_text_to_be_copied");
    clipboard.setPrimaryClip(clip);
    
  • 并粘贴:

    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    String pasteData = "";
    
     // If it does contain data, decide if you can handle the data.
    if (!(clipboard.hasPrimaryClip())) {
    
    } else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {
    
        // since the clipboard has data but it is not plain text
    
    } else {
    
        //since the clipboard contains plain text.
        ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
    
        // Gets the clipboard as text.
        pasteData = item.getText().toString(); 
    }
    

有关详情,请查看here

答案 1 :(得分:8)

蜂窝后的上述简短概述> = API 13:

public String readFromClipboard() {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard.hasPrimaryClip()) {
        android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
        android.content.ClipData data = clipboard.getPrimaryClip();
        if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) 
            return String.valueOf(data.getItemAt(0).getText());
    }
    return null;
}

答案 2 :(得分:7)

如果您只想复制并粘贴"一些代码进入您的应用程序,您可以使用以下内容。

复制

String textToCopy = etCodeWindow.getText().toString();

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(null, textToCopy);
if (clipboard == null) return;
clipboard.setPrimaryClip(clip);

粘贴

获取要粘贴的文字

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard == null) return;
ClipData clip = clipboard.getPrimaryClip();
if (clip == null) return;
ClipData.Item item = clip.getItemAt(0);
if (item == null) return;
CharSequence textToPaste = item.getText();
if (textToPaste == null) return;

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

将其插入光标位置

如果有选择,则选择将替换为粘贴文本。

int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
            textToPaste, 0, textToPaste.length());

注释

  • 此答案假定您不再支持pre-API 11.如果您再查看编辑历史记录。
  • 导入android.content.ClipboardManagerandroid.content.ClipData
  • 我曾经只是在一个衬里中获取粘贴文本,直到我发现ClipData有时会发生NPE崩溃。现在我要么使用try / catch块,要么更仔细地检查空值。

答案 3 :(得分:4)

我是这样做的。所有api级别的剪贴板管理器。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;


public class MyClipboardManager {

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public boolean copyToClipboard(Context context, String text) {
        try {
            int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData
                        .newPlainText(
                                context.getResources().getString(
                                        R.string.message), text);
                clipboard.setPrimaryClip(clip);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @SuppressLint("NewApi")
    public String readFromClipboard(Context context) {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                    .getSystemService(context.CLIPBOARD_SERVICE);
            return clipboard.getText().toString();
        } else {
            ClipboardManager clipboard = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            // Gets a content resolver instance
            ContentResolver cr = context.getContentResolver();

            // Gets the clipboard data from the clipboard
            ClipData clip = clipboard.getPrimaryClip();
            if (clip != null) {

                String text = null;
                String title = null;

                // Gets the first item from the clipboard data
                ClipData.Item item = clip.getItemAt(0);

                // Tries to get the item's contents as a URI pointing to a note
                Uri uri = item.getUri();

                // If the contents of the clipboard wasn't a reference to a
                // note, then
                // this converts whatever it is to text.
                if (text == null) {
                    text = coerceToText(context, item).toString();
                }

                return text;
            }
        }
        return "";
    }

    @SuppressLint("NewApi")
    public CharSequence coerceToText(Context context, ClipData.Item item) {
        // If this Item has an explicit textual value, simply return that.
        CharSequence text = item.getText();
        if (text != null) {
            return text;
        }

        // If this Item has a URI value, try using that.
        Uri uri = item.getUri();
        if (uri != null) {

            // First see if the URI can be opened as a plain text stream
            // (of any sub-type). If so, this is the best textual
            // representation for it.
            FileInputStream stream = null;
            try {
                // Ask for a stream of the desired type.
                AssetFileDescriptor descr = context.getContentResolver()
                        .openTypedAssetFileDescriptor(uri, "text/*", null);
                stream = descr.createInputStream();
                InputStreamReader reader = new InputStreamReader(stream,
                        "UTF-8");

                // Got it... copy the stream into a local string and return it.
                StringBuilder builder = new StringBuilder(128);
                char[] buffer = new char[8192];
                int len;
                while ((len = reader.read(buffer)) > 0) {
                    builder.append(buffer, 0, len);
                }
                return builder.toString();

            } catch (FileNotFoundException e) {
                // Unable to open content URI as text... not really an
                // error, just something to ignore.

            } catch (IOException e) {
                // Something bad has happened.
                Log.w("ClippedData", "Failure loading text", e);
                return e.toString();

            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }

            // If we couldn't open the URI as a stream, then the URI itself
            // probably serves fairly well as a textual representation.
            return uri.toString();
        }

        // Finally, if all we have is an Intent, then we can just turn that
        // into text. Not the most user-friendly thing, but it's something.
        Intent intent = item.getIntent();
        if (intent != null) {
            return intent.toUri(Intent.URI_INTENT_SCHEME);
        }

        // Shouldn't get here, but just in case...
        return "";
    }

}

答案 4 :(得分:1)

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
String copyedText = clipboard.getText();

答案 5 :(得分:0)

对于以编程方式复制粘贴的最佳简便方法是...

创建一个按钮,并将此代码复制到onclicklistener中。

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 

用于复制

clipboard.setText("which you want to copy"); 

用于粘贴

textview1.setText(clipboard.getText().toString()); 

答案 6 :(得分:0)

对于大多数Android设备(高于Honeycomb Android 3.0版),以下代码将起作用

用于将文本复制到剪贴板

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        ClipData clip = android.content.ClipData
                    .newPlainText("copyingToClipboard", "your text here to be copied to clipboard");
    clipboard.setPrimaryClip(clip);

用于从剪贴板复制

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.hasPrimaryClip() && (clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN) || clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_HTML))) {
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            String clipboardtext = item.getText().toString();
            Toast.makeText(Context,clipboardtext,Toast.LENGTH_LONG).show();
        }

如果剪贴板不包含任何数据,该代码将避免空值异常。

答案 7 :(得分:0)

这是@Suragch 答案的附录。

在 Kotlin 中:

        val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
        val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return

        binding.<your paste button camelCase id>.setOnClickListener {
            if (clipboard.hasPrimaryClip()) {
                binding.<your EditText camelCase id>.setText(textToPaste)
            }
        }

Fragment 内部:getSystemService() 是 Context 类上的一个方法,需要先调用 Context。可以通过使用 getContext() 或 getActivity() - Activity 也是一个上下文。

this.activity.getSystemService(...)
this.context.getSystemService(...)

或者:

activity.getSystemService(...)
context.getSystemService(...)

另外请记住仅安全 (?.) 或非空断言 (!!.) 调用。 如果您不想让用户存储任何数据,您可以指定它,例如:

if (clipboard.hasPrimaryClip() && textToPaste.isDigitsOnly())