在SDK11之前请使用android.text.ClipboardManager
Java代码
- import android.text.ClipboardManager;
- ……
- ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
- clipboardManager.setText("内容");
- if (clipboardManager.hasText()){
- clipboardManager.getText();
- }
从SDK11起android.text.ClipboardManager被废弃,使用它的子类android.content.ClipboardManager替代,同样被废弃还有setText/getText/hasText方法,使用setPrimaryClip/getPrimaryClip/hasPrimaryClip替代
Java代码
- import android.content.ClipboardManager;
- ……
- ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
- clipboardManager.setPrimaryClip(ClipData.newPlainText(null, "内容"));
- if (clipboardManager.hasPrimaryClip()){
- clipboardManager.getPrimaryClip().getItemAt(0).getText();
- }
- public class ClipboardUtils {
@SuppressWarnings("deprecation")
public static void copyToClipboard(Context context, String text){
android.text.ClipboardManager cbm = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cbm.setText(text);
}
@SuppressWarnings("deprecation")
public static CharSequence getClipboardText(Context context){
android.text.ClipboardManager cbm = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
return cbm.getText();
}
}
时间: 2024-11-05 20:35:23