首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

cocos2dx复制文字到剪贴板

2024-12-14 来源:要发发知识网

一、在基类Help.cpp文件中加入:

int copyToClipboard(const std::string& paras) {

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

        JniMethodInfo minfo;

        if (JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity","copyToClipboard", "(Ljava/lang/String;)I"))

        {

                jstring jstr = minfo.env->NewStringUTF(paras.c_str());

                int code = minfo.env->CallStaticIntMethod(minfo.classID, minfo.methodID, jstr);

                return code;

        }

#endif

        return -1;

}

二、在Help.h中加入:

//复制到剪贴板

int copyToClipboard(const std::string& paras);

三、在需要调用的地方直接调用,比如按下一个按钮复制:

void Spread::buttonEventWithCopy(cocos2d::Ref *ref, cocos2d::ui::Widget::TouchEventType type)

{

        if (type == cocos2d::ui::Widget::TouchEventType::ENDED)

        {

                copyToClipboard("copytext");

        }

}

四、编辑安卓包下org/cocos2dx/cpp/AppActivity.java文件

public class AppActivityextends Cocos2dxActivity {

        static AppActivitysgsActivity;

        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                sgsActivity =this;

        }

        //参数要加final关键字,否则内部类不能访问

        static public int copyToClipboard(final String text) {

                final Context context =sgsActivity;//参数要加final关键字,否则内部类不能访问

                try {

                        Log.d("cocos2dx","copyToClipboard " + text);

                        Runnable runnable =new Runnable() {

                                public void run() {

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

                                        android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text",text);

                                        clipboard.setPrimaryClip(clip);

                                }

                };

                //getSystemService运行所在线程必须执行过Looper.prepare()

                //否则会出现Can't create handler inside thread that has not called Looper.prepare()

                sgsActivity.runOnUiThread(runnable);

                }catch (Exception e) {

                        Log.d("cocos2dx","copyToClipboard error");

                        e.printStackTrace();

                        return -1;

                }

                return 0;

        }

}

显示全文