163

任何人都可以告诉我如何在按下按钮时将特定文本视图中的文本复制到剪贴板? 感谢名单:)如何在Android中将文本复制到剪贴板?

@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到剪贴板!请你帮助...

+0

的可能的复制[如何在我的Android应用程序复制文本?](http://stackoverflow.com/questions/238284/how-to-copy-text-programmatically-in-my-android -app) –

+0

https://stackoverflow.com/q/48791271/9274175请在coppy上回答这个问题 –

回答

290

使用ClipboardManager

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

确保您已导入android.content.ClipboardManager和NOT android.text.ClipboardManager。后者已弃用。 请查看link了解更多信息。

+3

这是针对API11 +而不适用于GB和低于 – Javier

+0

@zen我认为您可以对GB使用“setText”。 –

+0

import'android.content.ClipboardManager'和*** not ***'android.text.ClipboardManager'(我得到''android.text.ClipboardManager'已弃用'警告) – Atul

53

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

} 
+0

你可以添加必要的导入语句来使这个类工作吗? – merlin2011

+0

@ merlin2011做到了,我想我忘记了coerceToText(...)方法。 Sry那 –

+0

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

10

就用这个。它只适用于android api> = 11之前,你将不得不使用ClipData。

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

希望它可以帮助你:)

[更新2015年3月19日] 就像Ujjwal Singh表示,该方法setText现在已经过时,你应该使用,就像文档recommande它,setPrimaryClip(clipData)

+0

它显示错误_activity无法解析。 –

+1

究竟是什么错误?你可以发布吗? – Ektos974

+0

“_activity无法解析” –

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

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

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

+1

我不明白“context”是什么意思。你可以添加一个如何正确调用该方法的例子吗?谢谢。 –

+1

此外,它看起来像“上下文”的价值不被使用。那么为什么它必须作为参数传递? –

+0

@E_Blue感谢您的回复,我现在正在编辑 – vuhung3990

5

使用这个代码

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

非常感谢,它非常易于使用。 – kdblue

5

使用该功能用于复制到剪贴板

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

它适合我。非常简单和干净,谢谢 –

0

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