25

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

  1. 后台服务监听通知(完成)
  2. 收到通知时需要将文本复制到剪贴板(完成)
  3. 将文本粘贴到任何当前聚焦的字段,如果不可能,只需丢弃粘贴命令。

我知道如何用 复制文本ClipboardManager,但我不知道如何粘贴它。

4

8 回答 8

43

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

  • 复制:

    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(); 
    }
    

有关更多详细信息,请在此处查看

于 2013-10-04T09:22:16.313 回答
18

如果您只想将一些代码“复制并粘贴”到您的应用程序中,您可以使用以下内容。

#复制

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;
}

或在Kotlin中相同:

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

在光标位置插入

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

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());

#笔记

  • 此答案假定您不再支持 API 11 之前的版本。如果您支持,请查看编辑历史记录。
  • 导入android.content.ClipboardManagerandroid.content.ClipData.
  • 我以前只是将粘贴文本放在一个衬里,直到我发现 ClipData 有时会导致 NPE 崩溃。现在我要么使用 try/catch 块,要么更仔细地检查空值。
于 2017-03-31T02:16:51.470 回答
11

在蜂窝 >= 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;
}
于 2014-06-07T14:00:14.720 回答
5

我这样做。所有 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 "";
    }

}
于 2013-10-04T09:16:24.450 回答
2
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
String copyedText = clipboard.getText();
于 2013-10-04T09:09:08.743 回答
1

为了以编程方式复制粘贴的最佳和简单的方法是......

创建一个 Button 并将此代码复制到 onclicklistener 中。

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 

复印

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

用于粘贴

textview1.setText(clipboard.getText().toString()); 
于 2019-06-19T13:34:58.453 回答
0

这是@Suragch 答案的附录。

在科特林:

        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(...)

另外请记住只有安全 (?.) 或非空断言 (!!.) 调用。如果你不想让用户禁食你可以指定的任何数据,fe:

if (clipboard.hasPrimaryClip() && textToPaste.isDigitsOnly())
于 2021-07-14T14:00:12.533 回答
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();
        }

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

于 2020-06-06T18:15:56.490 回答