405

有人可以告诉我如何在按下按钮时将特定文本视图中的文本复制到剪贴板吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage);
    textView = (TextView) findViewById(R.id.textview);
    copyText = (Button) findViewById(R.id.bCopy);
    copyText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            String getstring = textView.getText().toString();
            
            // Help to continue :)
        }
    });
}

我想在bCopy按下按钮时将 TextView textView 中的文本复制到剪贴板。

4

27 回答 27

751

使用剪贴板管理器

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

确保您已导入android.content.ClipboardManager而不是android.text.ClipboardManager。后者已弃用。检查此链接以获取更多信息。

于 2013-10-08T16:59:22.577 回答
89

这里将文本复制到剪贴板的方法:

private void setClipboard(Context context, String text) {
  if(android.os.Build.VERSION.SDK_INT < 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("Copied Text", text);
    clipboard.setPrimaryClip(clip);
  }
}

此方法适用于所有 android 设备。

于 2015-02-28T10:17:10.480 回答
61

昨天我做了这门课。接受吧,它适用于所有 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;
import de.lochmann.nsafirewall.R;

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-08T16:59:47.483 回答
51

作为一个方便的 kotlin 扩展:

fun Context.copyToClipboard(text: CharSequence){
    val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = ClipData.newPlainText("label",text)
    clipboard.setPrimaryClip(clip)
}

更新:

如果你使用 ContextCompat 你应该使用:

ContextCompat.getSystemService(this, ClipboardManager::class.java)
于 2018-08-31T10:03:58.423 回答
17

对于 Jetpack 组合

val localClipboardManager = LocalClipboardManager.current
localClipboardManager.setText(AnnotatedString("Your text here"))
于 2021-09-11T07:22:05.607 回答
15

就用这个。它仅适用于 android api >= 11,在此之前您必须使用 ClipData。

ClipboardManager _clipboard = (ClipboardManager) _activity.getSystemService(Context.CLIPBOARD_SERVICE);
_clipboard.setText(YOUR TEXT);

希望它对你有帮助:)

[更新 3/19/2015] 就像Ujjwal Singh所说的那样,该方法setText现在已弃用,您应该按照文档的建议使用setPrimaryClip(clipData)

于 2013-12-23T16:07:07.600 回答
14

这可以像这样在 Kotlin 中完成:

var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var clip = ClipData.newPlainText("label", file.readText())
clipboard.setPrimaryClip = clip

file.readText()你的输入字符串在哪里。

于 2018-03-29T05:00:01.817 回答
8

使用此代码

   private ClipboardManager myClipboard;
   private ClipData myClip;
   TextView textView;
   Button copyText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage);
    textView = (TextView) findViewById(R.id.textview);
    copyText = (Button) findViewById(R.id.bCopy);
    myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

    copyText.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


           String text = textView.getText().toString();
           myClip = ClipData.newPlainText("text", text);
           myClipboard.setPrimaryClip(myClip);
           Toast.makeText(getApplicationContext(), "Text Copied", 
           Toast.LENGTH_SHORT).show(); 
        }
    });
}
于 2015-05-08T08:06:26.357 回答
7

使用此功能复制到剪贴板

public void copyToClipboard(String copyText) {
    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(copyText);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("Your OTP", copyText);
        clipboard.setPrimaryClip(clip);
    }
    Toast toast = Toast.makeText(getApplicationContext(),
            "Your OTP is copied", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 50, 50);
    toast.show();
    //displayAlert("Your OTP is copied");
}
于 2016-04-23T11:34:54.363 回答
6
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
@SuppressWarnings("deprecation")
@TargetApi(11)
public void onClickCopy(View v) {   // User-defined onClick Listener
    int sdk_Version = android.os.Build.VERSION.SDK_INT;
    if(sdk_Version < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(textView.getText().toString());   // Assuming that you are copying the text from a TextView
        Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
    }
    else { 
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        android.content.ClipData clip = android.content.ClipData.newPlainText("Text Label", textView.getText().toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
    }   
}
于 2014-12-06T21:58:42.710 回答
5

Kotlin 扩展功能 2021:

fun Context.copyToClipboard(text: CharSequence){
    val clipboard = ContextCompat.getSystemService(this,ClipboardManager::class.java)
    clipboard?.setPrimaryClip(ClipData.newPlainText("",text))
}
于 2021-04-30T22:30:53.360 回答
4

使用这个方法:

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

在 setPrimaryClip 的地方,我们还可以使用以下方法:

void    clearPrimaryClip()

清除剪贴板上的任何当前主剪辑。

ClipData    getPrimaryClip()

返回剪贴板上的当前主剪辑。

ClipDescription getPrimaryClipDescription()

返回剪贴板上当前主剪辑的描述,但不返回其数据的副本。

CharSequence    getText()

此方法已弃用。请改用 getPrimaryClip()。这将检索主剪辑并尝试将其强制转换为字符串。

boolean hasPrimaryClip()

如果剪贴板上当前有主剪辑,则返回 true。

于 2019-10-16T05:41:54.207 回答
3

使用 Jetpack Compose,这真的很容易:

AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))
于 2021-01-23T10:50:05.003 回答
2

使用 Java 的简单易用的 Android。

copytext.setOnClickListener(v -> {
            ClipboardManager myClipboard;
            myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
            ClipData myClip;
            String Text = "Hello World!";
            myClip = ClipData.newPlainText("text", Text);
            myClipboard.setPrimaryClip(myClip);

            Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();
        });
于 2021-08-22T09:57:21.383 回答
2
    String stringYouExtracted = referraltxt.getText().toString();
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted);

clipboard.setPrimaryClip(clip);
        Toast.makeText(getActivity(), "Copy coupon code copied to clickboard!", Toast.LENGTH_SHORT).show();
于 2019-04-17T09:09:34.603 回答
2

int sdk = android.os.Build.VERSION.SDK_INT;

    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText("" + yourMessage.toString());
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("message", "" + yourMessage.toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    }
于 2017-05-08T12:54:47.583 回答
1

用于将文本复制到剪贴板的简单 Kotlin 扩展功能

fun Context.copyToClipboard(clipLabel: String, text: CharSequence){
    val clipboard = ContextCompat.getSystemService(this, ClipboardManager::class.java)
    clipboard?.setPrimaryClip(ClipData.newPlainText(clipLabel, text))

    toast("Copied $clipLabel")
}
于 2021-11-30T17:52:43.883 回答
1
 ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);
于 2020-08-23T15:55:15.117 回答
1

==>点击查看复制内容太容易了。

-> 将文本存储到字符串变量中。

-> 制作 ClipboardManager 的变量

-> 制作 ClipData 的变量

-> 必须从包中导入为“android.content”。

-> 将剪辑设置为 clipboard.setPrimaryclick。

-> 完成。

前任。

import android.content.ClipboardManager;

import android.content.ClipData;





    stringNodetxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String stringNodeCopied= stringNodetxt.getText().toString();

            ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = android.content.ClipData.newPlainText("Copied", stringNodeCopied);

            clipboard.setPrimaryClip(clip);
            Toast.makeText(getBaseContext(), "copied to clipboard!", Toast.LENGTH_SHORT).show();
        }
    });
于 2021-08-25T11:28:41.183 回答
0

搜索剪贴板列表首先获取剪贴板对象,如下所示:

private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

然后通过此功能检查剪贴板中是否有任何数据:

fun isClipboardContainsData() : Boolean{
        return when{
            !clipboard.hasPrimaryClip() -> false
            else -> true
        }
    }

然后使用此函数遍历剪贴板对象,如下所示:

fun searchClipboard() : ClipData.Item? {
        return if (isClipboardContainsData()){

            val items = clipboard.primaryClip
            val clipboardSize = items?.itemCount ?: 0
            for (i in 0..clipboardSize) {
                val item = items?.getItemAt(i)
                return if (item != null){
                       return item
                }else
                    null
            }
            return null
        }else
            null

    }

在这里你可以看到 searchClipboard Item 将返回一个 ClipData.Item 类型的项目,剪贴板包含一个 ClipData.Item 列表,如果你通过剪贴板的实现,你会发现关于 ClipData.Item 的内容:

public static class Item {
    final CharSequence mText;
    final String mHtmlText;
    final Intent mIntent;
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    Uri mUri;
}

因此,您可以在剪贴板项目中保存的内容可能是以下类型:

  1. 字符序列
  2. 细绳
  3. 意图(这支持复制应用程序快捷方式)
  4. Uri(用于从内容提供者复制复杂数据)
于 2020-12-20T11:21:16.700 回答
0

您可以在 onclick 按钮事件时执行此复制到剪贴板功能。所以把这些代码行放在你的按钮 onClickListerner

android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clipData = android.content.ClipData.newPlainText("Text Label", ViewPass.getText().toString());
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(),"Copied from Clipboard!",Toast.LENGTH_SHORT).show();
于 2020-03-27T19:05:30.970 回答
0

试试下面的代码。它将支持最新的 API:

ClipboardManager clipboard = (ClipboardManager) context.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))
                            {
                                String url= (String) clipboard.getText();
                                searchText.setText(url);
                                System.out.println("data="+data+"description="+description+"url="+url);
                            }}
于 2019-05-04T03:19:54.863 回答
0

Kotlin我有一个扩展

fun Context.copyToClipboard(text: String) {
  val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
  val clip =
    ClipData.newPlainText(getString(R.string.copy_clipboard_label, getString(R.string.app_name)),text)
  clipboard.setPrimaryClip(clip)
}
于 2020-10-03T12:00:57.477 回答
0

要在 Android 中复制任何文本:

            TextView text = findViewById(R.id.text_id);
            ImageView icons = findViewById(R.id.copy_icon);

            icons.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);

                    Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
                }
            });
于 2020-10-22T01:24:15.623 回答
0

Kotlin 辅助方法附加单击以在 TextView 上复制文本

将此方法放在 Util 类中的某个位置。此方法将 textview 上的单击侦听器附加到单击该 textView 时将 textView 的内容复制到 clipText

/**
 * Param:  cliplabel, textview, context
 */
fun attachClickToCopyText(textView: TextView?, clipLabel: String, context: Context?) {
    if (textView != null && null != context) {
        textView.setOnClickListener {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clip = ClipData.newPlainText(clipLabel, textView!!.text)
            clipboard.primaryClip = clip
            Snackbar.make(textView,
                    "Copied $clipLabel", Snackbar.LENGTH_LONG).show()
        }
    }

}
于 2019-07-18T12:10:57.957 回答
0

如果您想缩短使用时间:

ClipData clip = ClipData.newPlainText(label, text);
((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(clip);
于 2021-05-01T19:36:00.937 回答
-1

只需编写以下代码:

clipboard.setText(getstring);
于 2020-03-29T10:49:56.873 回答