【问题标题】:Button to copy the value of a string to the clipboard用于将字符串的值复制到剪贴板的按钮
【发布时间】:2012-09-28 14:34:01
【问题描述】:

我正在修改旧的 Android 应用程序。我有一个 GPS lat 和 long 存储在一个字符串值中,并在解析时在一个不可编辑的文本框中显示给用户。我想添加一个按钮,它只接受字符串的值,并将其复制到剪贴板。

我看过这个:How to copy text programmatically in my Android app?

但不知道如何实现它。任何帮助都会很棒,我最近在这方面没有太多的发展!

谢谢

编辑:

    //Set button (inside oncreate method)
    Button button = (Button)this.findViewById(R.id.buttoncopylocation);
    button.setOnClickListener(this);

//Code added in onClick method
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    ClipboardManager clipboard = (ClipboardManager)   getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("Copied", mycoords);
    clipboard.setPrimaryClip(clip);
}

我收到此错误:http://i.imgur.com/sQ4um.jpg

【问题讨论】:

  • 如果您将那段代码发布到您想在剪贴板中设置文本的位置,将会很有帮助。
  • @Trickster 我添加了代码来协助。
  • 您的目标是哪个 API 级别? ClipData 从 API 级别 11 开始可用。
  • 看看this discussion。另请参阅this one 以了解最小和目标 sdk 版本

标签: android string button clipboard


【解决方案1】:

如果只是Text,就很简单了。

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

更多信息请查看this link

【讨论】:

  • 这行得通,谢谢(虽然略有改动): public void onClick(View arg0) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager)getSystemService(CLIPBOARD_SERVICE);剪贴板.setText(mycoords); Toast.makeText(getApplicationContext(), "文本复制到剪贴板", Toast.LENGTH_SHORT).show();
【解决方案2】:

提供之前的上下文

getSystemService(Context.CLIPBOARD_SERVICE);

喜欢

Context context = ...;
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多