1.点击按钮复制固定内容
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"/>
设置一个弹窗的页面xml
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/copy_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/empty"
android:text="复制" />
private PopupWindow popupWindow;
private ClipboardManager clipboardManager;
androidx.appcompat.widget.AppCompatButton buttonCopy = findViewById(R.id.button);
// 设置点击事件监听器
buttonCopy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 要复制的文本
String textToCopy = "这里是固定的内容或者你要复制的文字";
// 获取剪贴板管理器
clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", textToCopy);
clipboardManager.setPrimaryClip(clip);
Toast.makeText(CopyActivity.this, "文本已复制", Toast.LENGTH_SHORT).show();
}
});
2.长按文本复制功能
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="长按复制这段文字"
android:padding="16dp" />
TextView textView = findViewById(R.id.textView);
textView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// 显示菜单
showPopupWindow(v);
return true;
}
});
}
private void showPopupWindow(View anchorView) {
// 获取LayoutInflater
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// 从自定义布局文件inflate弹出菜单布局
View popupView = inflater.inflate(R.layout.popup_menu, null);
// 创建PopupWindow实例,指定其宽度和高度为内容自适应
popupWindow = new PopupWindow(popupView,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
true);
// 设置PopupWindow的布局
popupWindow.setContentView(popupView);
// 设置点击外部消失
popupWindow.setOutsideTouchable(true);
// 设置弹出窗口的背景,这一步必须要有,否则点击外部无法让PopupWindow消失
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.RED));
// 显示PopupWindow,可以使用不同的方法来定位,这里是简单地显示在锚点视图下方
popupWindow.showAsDropDown(anchorView);
// 找到并设置复制按钮的点击事件
popupView.findViewById(R.id.copy_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView textView = findViewById(R.id.textView);
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", textView.getText().toString());
clipboardManager.setPrimaryClip(clip);
Toast.makeText(CopyActivity.this, "文本已复制", Toast.LENGTH_SHORT).show();
popupWindow.dismiss();
}
});
}
}