且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android如何从PrimaryClipChanged的剪贴板中获取字符串?

更新时间:2023-11-14 23:26:34

我建议如下添加侦听器,而不是创建新的类。我已经包括了如何从ClipData中获取文本。

I would suggest adding the listener as follows instead of creating a new class. I have included how to get text from the ClipData.

您提到无法在侦听器中访问上下文,我在下面的代码中添加了注释,显示了如何

You mention being unable to access your context in the listener, I've added a comment within the code below showing how to do so.

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {

    @Override
    public void onPrimaryClipChanged() {
        ClipData clipData = clipBoard.getPrimaryClip();
        ClipData.Item item = clipData.getItemAt(0);
        String text = item.getText().toString();

        // Access your context here using YourActivityName.this
    }
});