Android how to get string from clipboard onPrimaryClipChanged?

核能气质少年 提交于 2019-12-09 17:27:44

问题


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");
    }
}

The listener is initialized as follows:

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

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.


回答1:


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
    }
});


来源:https://stackoverflow.com/questions/38214257/android-how-to-get-string-from-clipboard-onprimaryclipchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!