gpt4 book ai didi

android - 如何在phonegap中创建 toast ?

转载 作者:IT老高 更新时间:2023-10-28 23:20:56 25 4
gpt4 key购买 nike

如何使用 phonegap/cordova 在 android 应用程序中创建 toast?

谢谢!

最佳答案

首先创建一个ToastPlugin.java

package com.company.plugins;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;
import android.widget.Toast;

public class ToastPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {

String message = args.getString(0);

// used to log the text and can be seen in LogCat
Log.d("Toast Plugin", "Calling the Toast...");
Log.d("Toast Plugin", message);

if (action.equals("shortToast")) {
this.shortToast(message, callbackContext);
return true;
} else if (action.equals("longToast")) {
this.longToast(message, callbackContext);
return true;
}
return false;
}

private void shortToast(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
Toast.makeText(cordova.getActivity().getApplicationContext(),
message, Toast.LENGTH_SHORT).show();
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}

private void longToast(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
Toast.makeText(cordova.getActivity().getApplicationContext(),
message, Toast.LENGTH_LONG).show();
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}


然后创建一个 toastPlugin.js

//Plugin file should be always after cordova.js
//There is always better way to create, but this also works

window.shortToast = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "ToastPlugin", "shortToast", [ str ]);
};

window.longToast = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "ToastPlugin", "longToast", [ str ]);
};


在你的项目中链接这些文件,现在你可以在 JavaScript 中调用:

  • shortToast("这里有简短的 Toast 消息...");
  • longToast("这里的 toast 长消息...");

关于android - 如何在phonegap中创建 toast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14724053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com