在Android上从剪贴板粘贴

9

我写了一个代码,它可以将计算器中的答案复制到剪贴板上,然后关闭计算器并打开另一个窗口。下面的代码可以用于粘贴答案:

    textOut2= (TextView) findViewById(R.id.etInput1);
    final ClipboardManager clipBoard= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
    textOut2.setText(clipBoard.getText());

但它从来没有起作用。可能出了什么问题?附注:我知道文本是复制的,因为我可以使用长按粘贴,但我想要自动完成。并且是否有可能给复制的文本指定一个特定的名称?这样会更容易将单词粘贴到不同的TextView中,因为我有很多不同的TextView。

3个回答

15

public CharSequence getText () 自API Level 11起已被弃用。 使用getPrimaryClip()代替。这将检索主要剪贴板并尝试将其强制转换为字符串。

String textToPaste = null;

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

if (clipboard.hasPrimaryClip()) {
    ClipData clip = clipboard.getPrimaryClip();

    // if you need text data only, use:
    if (clip.getDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))
        // WARNING: The item could cantain URI that points to the text data.
        // In this case the getText() returns null and this code fails!
        textToPaste = clip.getItemAt(0).getText().toString();

    // or you may coerce the data to the text representation:
    textToPaste = clip.getItemAt(0).coerceToText(this).toString();
}

if (!TextUtils.isEmpty(textToPaste))
     ((TextView)findViewById(R.id.etInput1)).setText(textToPaste);

你可以通过ClipData.addItem()添加额外的带文本的ClipData.Item项目,但没有办法分辨它们。


3

试试这个

textOut2= (TextView) findViewById(R.id.etInput1);
final ClipboardManager clipBoard= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
String temp = new String;
temp = clipBoard.getText().toString();
textOut2.setText(temp);

1
在 Kotlin 中:
        val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
        val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return

        binding.<your EditText camelCase id>.setText(textToPaste)

在Fragment内部:getSystemService()是Context类的一个方法,必须先调用Context。可以通过使用getContext()或者另一种方法,即getActivity() - Activity也是一个Context。

this.activity.getSystemService(...)
this.context.getSystemService(...)

或者:

activity.getSystemService(...)
context.getSystemService(...)

另外要记住只使用安全的 (?.) 或非空断言 (!!.) 调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接