有人能告诉我如何复制在一个特定的文本视图到剪贴板,当一个按钮被按下?

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

我想复制文本在TextView TextView到剪贴板时,按钮bCopy按下。


使用ClipboardManager

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

确保你导入了android.content.ClipboardManager而不是android.text.ClipboardManager。后者不建议使用。 查看此链接以获取更多信息。


昨天我做了这门课。拿去吧,它适用于所有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 "";
    }

}

就用这个。它只适用于android api >= 11之前,你必须使用一个ClipData。

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

希望对你有所帮助:)

(更新3/19/2015) 就像Ujjwal Singh说的,setText方法已经弃用了,你应该使用setPrimaryClip(clipData),就像文档建议的那样


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

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

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


使用这段代码

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

使用此函数复制到剪贴板

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

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

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

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

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


作为一个方便的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)

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

试试下面的代码。它将支持最新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);
                            }}

Kotlin助手方法附加单击复制TextView上的文本

把这个方法放在Util类中的某个地方。这个方法附加点击监听器的textview复制内容的textview到一个clipText点击该textview

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

}

使用这个方法:

 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。


您可以在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();

只需编写以下代码:

clipboard.setText(getstring);

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

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

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

要搜索剪贴板列表,首先像这样获取剪贴板对象:

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的项。项时,剪贴板包含ClipData的列表。项目,如果你学习clipboard的实现这就是关于ClipData的内容。单品:

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

所以你可以在剪贴板项目中保存的内容类型可以是:

CharSequence进行 字符串 意图(支持复制应用程序快捷方式) Uri(用于从内容提供程序复制复杂数据)


使用Jetpack Compose,这非常简单:

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

Kotlin扩展函数2021:

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

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

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

简单和容易的Android使用Java。

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

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

存储文本到字符串变量。

->创建ClipboardManager的变量

->制作ClipData的变量

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

->设置剪辑到clipboard.setPrimaryclick。

- >完成。

ex.

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

对于Jetpack编写

val localClipboardManager = LocalClipboardManager.current
localClipboardManager.setText(AnnotatedString("Your text here"))

简单的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")
}

    import android.content.ClipData
    import android.content.ClipboardManager
    import android.content.Context

    val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    clipboardManager.setPrimaryClip(ClipData.newPlainText("text","this is copied...paste it" ))

如果你想从edittext中复制文本,那么首先创建edittext

    EditText mResultEt = findViewById(R.id.resultEt);

然后创建一个按钮,点击后,我们可以复制这些文本

    ImageButton copyClipBoard = findViewById(R.id.btn_copy);

然后使用按钮的监听器

Java

copyClipBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager clipboardManager = (ClipboardManager)
                        getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("nonsense_data",
                        mResultEt.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
            }
        });

科特林

btn1.setOnClickListener{
            val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText(
                "nonsense_data",
                content_et.getText().toString()
            )
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(this@MainActivity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show()

        }

确保导入这个

import android.content.ClipboardManager;

不要导入这个

android.text.ClipboardManager

在芬兰湾的科特林 只需在按钮内输入此代码。此代码适用于Fragment类。

var myClipboard = getSystemService(requireContext(), ClipboardManager::class.java) as ClipboardManager
            val copyText = quotes//quotes is actual text(I want to copy) that is assign in copyText.
            val clip = ClipData.newPlainText("Copied",copyText)
            myClipboard.setPrimaryClip(clip)
            Toast.makeText(requireActivity(), "Copied", Toast.LENGTH_SHORT).show()

Kotlin中最简单的代码-

val myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val myClip: ClipData = ClipData。newPlainText(“标签”,“文本”) myClipboard.setPrimaryClip (myClip)

注意:确保你导入了android.content.ClipboardManager而不是android.text.ClipboardManager。后者不建议使用。