如何在Android中将文本复制到剪贴板?


313

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

    @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中的Text复制到剪贴板。



stackoverflow.com/q/48791271/9274175请在coppy上回答这个问题
Yash Kale

Answers:


590

使用ClipboardManager

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

确保您已导入android.content.ClipboardManager并且不是android.text.ClipboardManager。不建议使用。检查此链接以获取更多信息。


3
这仅适用于API11 +,不适用于GB及以下版本
Javier

48
“标签”是做什么用的?
Android开发人员

19
@androiddeveloper“ label”参数的说明:stackoverflow.com/questions/33207809/…–
smg

3
@smg那么对开发人员来说呢?但是,为什么它显示给用户呢?
Android开发人员

7
在androidx中,它实际上变为ClipboardManager clipboard = getSystemService(getContext(), ClipboardManager.class);
HoratioCain '19

72

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

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设备。


2
我不明白“上下文”的含义。您可以添加一个示例来说明如何正确调用该方法吗?谢谢。
E_Blue

1
而且看起来好像没有使用“ context”的值。那么为什么必须将其作为参数传递呢?
E_Blue

嗨,伙计们需要上下文来调用getSystemService
vuhung3990'1

@E_Blue context.getSystemService(Context.CLIPBOARD_SERVICE)??? 真???
androidStud

1
@E_Blue看起来您是一位天真的android开发人员,正在询问上下文。嗯,这也不是问题,但只要注意自己的语气,然后对事物进行一些研究/研究。
androidStud

57

昨天我上了这堂课。接受,适用于所有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 "";
    }

}

您可以添加必要的import语句来使此类工作吗?
merlin2011

@ merlin2011做到了,认为我忘记了coerceToText(...)方法。抱歉
2014年

“ coerceToText”是做什么的?另外,是否可以将其他类型的数据复制/粘贴到剪贴板(例如:位图)?
android开发人员

1
@AS为什么您自己编写了corceToText方法?!其已可提供API请参见developer.android.com/reference/android/content/...
Hardik

但是我认为开发人员有时间停止对API17的支持。较老的类型没有多少单位,他们不倾向于下载新的应用程序吗?例如,我在帆船中使用长者单元进行导航,其他所有内容都被抹掉了。我不介意将这些单位误扔掉吗?
JanBergström19年

23

作为方便的Kotlin扩展:

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

更新:

如果使用ContextCompat,则应使用:

ContextCompat.getSystemService(this, ClipboardManager::class.java)

1
API现在已更改为剪贴板管理器= getSystemService(context,ClipboardManager :: class.java)
Per Christian Henden

它实际上更改为context.getSystemService(ClipboardManager::class.java)您所指向的是ContextCompat签名,不是吗?感谢您的反馈
crgarridos

13

只是使用这个。它仅适用于android api> = 11,然后您必须使用ClipData。

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

希望它对您有所帮助:)

[UPDATE 3/19/2015]就像Ujjwal Singh所说的那样,setText现在不赞成使用该方法,就像文档要求的那样,您应该使用setPrimaryClip(clipData)


1
那就是我的变量名。如果您参加活动,请使用 (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); _clipboard.setText(YOUR TEXT);
Ektos974 2014年

1
已弃用-请勿使用setTextuse ClipData+setPrimaryClip
Ujjwal Singh 2014年

对我来说,使用setPrimaryClip
Praneeth

11

可以这样在Kotlin中完成:

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

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


7

使用此代码

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

非常感谢,它非常易于使用。
iamkdblue

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

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

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

2

使用此方法:

 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。


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

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

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

}

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

0

只需编写以下代码:

clipboard.setText(getstring);

您忘了初始化clipboard。但是谢谢setText。已弃用,请使用val clip = ClipData.newPlainText(null, text) clipboard.setPrimaryClip(clip)
CoolMind

-1

对于科特林

 ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.