Skip to content Skip to sidebar Skip to footer

How To Create Toast In Phonegap?

How to create toast in android application using phonegap / cordova? Thanx!

Solution 1:

First create a 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;

publicclassToastPluginextendsCordovaPlugin {
    @Overridepublicbooleanexecute(String action, JSONArray args,
            CallbackContext callbackContext) throws JSONException {

        String message = args.getString(0);

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

        if (action.equals("shortToast")) {          
            this.shortToast(message, callbackContext);
            returntrue;
        } elseif (action.equals("longToast")) {
            this.longToast(message, callbackContext);
            returntrue;
        }
        returnfalse;
    }

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

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

Then create a toastPlugin.js

//Plugin file should be always after cordova.js//There is always better way to create, but this also workswindow.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 ]);
};

Link these files in your project, now you can call in JavaScript as :

  • shortToast("Short Toast Message Here...");
  • longToast("Long Toast Message Here...");

Solution 2:

Solution 3:

Looking for a universal iOS/Android/WP8 Toast plugin, checkout this one: http://www.x-services.nl/phonegap-toast-plugin/796

Post a Comment for "How To Create Toast In Phonegap?"