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

时间:2013-10-08 16:55:09

标签: android clipboard copy-paste clipboardmanager clipboard-interaction

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

@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复制到剪贴板!请帮忙......

22 个答案:

答案 0 :(得分:445)

使用ClipboardManager

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

确保您已导入android.content.ClipboardManager而非android.text.ClipboardManager。后者已被弃用。 请查看此link以获取更多信息。

答案 1 :(得分:58)

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

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 :(得分:55)

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

}

答案 3 :(得分:12)

请使用此功能。它只适用于android api&gt; = 11之前你必须使用ClipData。

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

希望它能帮到你:)。

[2015年3月19日更新]   就像Ujjwal Singh所说的方法setText现在已被弃用,您应该使用,就像文档推荐的那样,setPrimaryClip(clipData)

答案 4 :(得分:8)

作为方便的Kotlin扩展名:

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

答案 5 :(得分: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();
    }   
}

答案 6 :(得分:6)

使用此代码

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

答案 7 :(得分:6)

使用此功能复制到剪贴板

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

答案 8 :(得分:6)

这可以在Kotlin中完成,如下所示:

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

file.readText()是您的输入字符串。

答案 9 :(得分:2)

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

AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))

答案 10 :(得分:1)

Kotlin 扩展功能 2021:

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

答案 11 :(得分:1)

使用此方法:

 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。

答案 12 :(得分:0)

如果你想让它更短,请使用:

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

答案 13 :(得分: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 的内容:< /p>

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. Intent(支持复制应用程序快捷方式)
  4. Uri(用于从内容提供商复制复杂数据)

答案 14 :(得分:0)

要在Android中复制任何文本:

(?<=#)[A-Za-z0-9_-]*

答案 15 :(得分:0)

科特林中,我对此有一个扩展名

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

答案 16 :(得分:0)

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

答案 17 :(得分:0)

只需编写以下代码:

clipboard.setText(getstring);

答案 18 :(得分: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();

答案 19 :(得分:0)

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

将此方法放在Util类中的某个位置。此方法将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()
        }
    }

}

答案 20 :(得分: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);
                            }}

答案 21 :(得分:0)

if(!context.isFinishing()){

  builder.show();
}