Android如何从PrimaryClipChanged的剪贴板中获取字符串? [英] Android how to get string from clipboard onPrimaryClipChanged?

查看:133
本文介绍了Android如何从PrimaryClipChanged的剪贴板中获取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用以下侦听器将文本复制到剪贴板中:

I'm trying to get text copied into the clipboard using the following listener:

import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import com.orhanobut.logger.Logger;

public class ClipboardListener implements OnPrimaryClipChangedListener
{

    public void onPrimaryClipChanged()
    {
        // do something useful here with the clipboard
        // use getText() method
        Logger.d("Clipped");
    }
}

侦听器初始化如下:

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener());

将文本复制到剪贴板中之后 onPrimaryClipChanged 被触发,但是我不知道如何使用 ClipboardManager.getPrimaryClip(),因为该方法在上下文中不可用,并且未在 onPrimaryClipChanged 。

After the text is copied into the clipboard onPrimaryClipChanged is fired, but I don't know how to get the copied text in this method using ClipboardManager.getPrimaryClip() because the method is not available from the context and is not passed in the param of onPrimaryClipChanged.

推荐答案

我建议如下添加侦听器,而不是创建新的类。我已经包括了如何从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
    }
});

这篇关于Android如何从PrimaryClipChanged的剪贴板中获取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆