如何在phonegap中创建吐司?

时间:2013-02-06 07:52:36

标签: android cordova toast

如何使用phonegap / cordova在Android应用程序中创建吐司?

感谢名单!

3 个答案:

答案 0 :(得分:19)

首先创建一个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(“Short Toast Message Here ...”);
  • longToast(“Long Toast Message Here ...”);

答案 1 :(得分:7)

PhoneGap-Toast是PhoneGap的开源(MIT许可)桥接器,允许您执行此操作。

答案 2 :(得分:3)

寻找通用的iOS / Android / WP8 Toast插件,请查看以下内容:http://www.x-services.nl/phonegap-toast-plugin/796