总共2步实现:
1.创建CopyButtonLibrary.java
package com.huatec.danyizz.utils;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
import static android.content.Context.CLIPBOARD_SERVICE;
/**
* Created by elha on 3/19/2018.
*/
public class CopyButtonLibrary {
private ClipboardManager myClipboard;
private ClipData myClip;
private Context context;
private TextView textView;
public CopyButtonLibrary(Context context, TextView textView) {
this.context = context;
this.textView = textView;
}
public void init() {
myClipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
String text;
text = textView.getText().toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(context, text + " 已复制", Toast.LENGTH_SHORT).show();
}
}
2.使用:
//监听点击事件
final TextView textView = findViewById(R.id.textview);//文字
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//传入需要复制的文字的控件
CopyButtonLibrary copyButtonLibrary = new CopyButtonLibrary(getApplicationContext(),textView);
copyButtonLibrary.init();
}
});
效果图: