Compare commits

...
3 Commits
7 changed files with 172 additions and 13 deletions
+34 -1
View File
@@ -151,7 +151,7 @@ You can copy-paste these lines of code for a quick test:
Since 2.1.0 you can add pixels to move the toast up or down.
Note that `showWithOptions` can be used instead of the functions above, but it's not useful unless you want to pass `addPixelsY`.
```js
function showTop() {
function showBottom() {
window.plugins.toast.showWithOptions(
{
message: "hey there",
@@ -174,6 +174,35 @@ function hide() {
}
```
### Receiving a callback when a Toast is tapped
On iOS and Android the success handler of your `show` function will be notified (again) when the toast was tapped.
So the first time the success handler fires is when the toast is shown, and in case the user taps the toast it will be
called again. You can distinguish between those events of course:
```js
window.plugins.toast.showWithOptions(
{
message: "hey there",
duration: "short",
position: "bottom",
addPixelsY: -40, // (optional) added a negative value to move it up a bit (default 0)
data: {'foo','bar'} // (optional) pass in a JSON object here (it will be sent back in the success callback below)
},
// implement the success callback
function(result) {
if (result && result.event) {
console.log("The toast was tapped");
console.log("Event: " + result.event); // will be defined, with a value of "touch" when it was tapped by the user
console.log("Message: " + result.message); // will be equal to the message you passed in
console.log("data.foo: " + result.data.foo); // .. retrieve passed in data here
} else {
console.log("The toast has been shown");
}
}
);
```
### WP8 quirks
The WP8 implementation needs a little more work, but it's perfectly useable when you keep this in mind:
* You can't show two Toasts simultaneously.
@@ -188,6 +217,10 @@ The Android code was entirely created by me.
For iOS most credits go to this excellent [Toast for iOS project by Charles Scalesse] (https://github.com/scalessec/Toast).
## 6. CHANGELOG
2.3.2: The click event introduced with 2.3.0 did not work with Android 5+.
2.3.0: The plugin will now report back to JS if Toasts were tapped by the user.
2.0.1: iOS messages are hidden when another one is shown. [Thanks Richie Min!](https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin/pull/13)
2.0: WP8 support
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cordova-plugin-x-toast",
"version": "2.2.3",
"version": "2.3.2",
"description": "This plugin allows you to show a Toast. A Toast is a little non intrusive buttonless popup which automatically disappears.",
"cordova": {
"id": "cordova-plugin-x-toast",
+1 -1
View File
@@ -2,7 +2,7 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-x-toast"
version="2.2.3">
version="2.3.2">
<name>Toast</name>
+102 -5
View File
@@ -2,9 +2,13 @@ package nl.xservices.plugins;
import android.os.Build;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -24,7 +28,14 @@ public class Toast extends CordovaPlugin {
private static final String ACTION_SHOW_EVENT = "show";
private static final String ACTION_HIDE_EVENT = "hide";
private static final int GRAVITY_TOP = Gravity.TOP|Gravity.CENTER_HORIZONTAL;
private static final int GRAVITY_CENTER = Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL;
private static final int GRAVITY_BOTTOM = Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL;
private static final int BASE_TOP_BOTTOM_OFFSET = 20;
private android.widget.Toast mostRecentToast;
private ViewGroup viewGroup;
private static final boolean IS_AT_LEAST_ANDROID5 = Build.VERSION.SDK_INT >= 21;
@@ -36,6 +47,7 @@ public class Toast extends CordovaPlugin {
if (ACTION_HIDE_EVENT.equals(action)) {
if (mostRecentToast != null) {
mostRecentToast.cancel();
getViewGroup().setOnTouchListener(null);
}
callbackContext.success();
return true;
@@ -52,10 +64,11 @@ public class Toast extends CordovaPlugin {
final String duration = options.getString("duration");
final String position = options.getString("position");
final int addPixelsY = options.has("addPixelsY") ? options.getInt("addPixelsY") : 0;
final JSONObject data = options.has("data") ? options.getJSONObject("data") : null;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
android.widget.Toast toast = android.widget.Toast.makeText(
final android.widget.Toast toast = android.widget.Toast.makeText(
IS_AT_LEAST_ANDROID5 ? cordova.getActivity().getWindow().getContext() : cordova.getActivity().getApplicationContext(),
message,
"short".equals(duration) ? android.widget.Toast.LENGTH_SHORT : android.widget.Toast.LENGTH_LONG);
@@ -67,19 +80,81 @@ public class Toast extends CordovaPlugin {
// } catch (Exception ignore) {
// }
if ("top".equals(position)) {
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 20 + addPixelsY);
toast.setGravity(GRAVITY_TOP, 0, BASE_TOP_BOTTOM_OFFSET + addPixelsY);
} else if ("bottom".equals(position)) {
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20 - addPixelsY);
toast.setGravity(GRAVITY_BOTTOM, 0, BASE_TOP_BOTTOM_OFFSET - addPixelsY);
} else if ("center".equals(position)) {
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, addPixelsY);
toast.setGravity(GRAVITY_CENTER, 0, addPixelsY);
} else {
callbackContext.error("invalid position. valid options are 'top', 'center' and 'bottom'");
return;
}
// On Android >= 5 you can no longer rely on the 'toast.getView().setOnTouchListener',
// so created something funky that compares the Toast position to the tap coordinates.
if (IS_AT_LEAST_ANDROID5) {
getViewGroup().setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() != MotionEvent.ACTION_DOWN) {
return false;
}
if (mostRecentToast == null || !mostRecentToast.getView().isShown()) {
getViewGroup().setOnTouchListener(null);
return false;
}
float w = mostRecentToast.getView().getWidth();
float startX = (view.getWidth() / 2) - (w / 2);
float endX = (view.getWidth() / 2) + (w / 2);
float startY;
float endY;
float g = mostRecentToast.getGravity();
float y = mostRecentToast.getYOffset();
float h = mostRecentToast.getView().getHeight();
if (g == GRAVITY_BOTTOM) {
startY = view.getHeight() - y - h;
endY = view.getHeight() - y;
} else if (g == GRAVITY_CENTER) {
startY = (view.getHeight() / 2) + y - (h / 2);
endY = (view.getHeight() / 2) + y + (h / 2);
} else {
// top
startY = y;
endY = y + h;
}
float tapX = motionEvent.getX();
float tapY = motionEvent.getY();
final boolean tapped = tapX >= startX && tapX <= endX &&
tapY >= startY && tapY <= endY;
if (tapped) {
getViewGroup().setOnTouchListener(null);
return returnTapEvent(message, data, callbackContext);
}
return false;
}
});
} else {
toast.getView().setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return motionEvent.getAction() == MotionEvent.ACTION_DOWN && returnTapEvent(message, data, callbackContext);
}
});
}
toast.show();
mostRecentToast = toast;
callbackContext.success();
PluginResult pr = new PluginResult(PluginResult.Status.OK);
pr.setKeepCallback(true);
callbackContext.sendPluginResult(pr);
}
});
@@ -90,10 +165,32 @@ public class Toast extends CordovaPlugin {
}
}
private boolean returnTapEvent(String message, JSONObject data, CallbackContext callbackContext) {
final JSONObject json = new JSONObject();
try {
json.put("event", "touch");
json.put("message", message);
json.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
callbackContext.success(json);
return true;
}
// lazy init and caching
private ViewGroup getViewGroup() {
if (viewGroup == null) {
viewGroup = (ViewGroup) ((ViewGroup) cordova.getActivity().findViewById(android.R.id.content)).getChildAt(0);
}
return viewGroup;
}
@Override
public void onPause(boolean multitasking) {
if (mostRecentToast != null) {
mostRecentToast.cancel();
getViewGroup().setOnTouchListener(null);
}
this.isPaused = true;
}
+2 -1
View File
@@ -1,11 +1,12 @@
#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
@interface UIView (Toast)
// each makeToast method creates a view and displays it as toast
- (void)makeToast:(NSString *)message;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)interval position:(id)position;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position addPixelsY:(int)addPixelsY;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position addPixelsY:(int)addPixelsY data:(NSDictionary*)data commandDelegate:(id <CDVCommandDelegate>)commandDelegate callbackId:(NSString *)callbackId;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)interval position:(id)position image:(UIImage *)image;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)interval position:(id)position title:(NSString *)title;
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)interval position:(id)position title:(NSString *)title image:(UIImage *)image;
+23 -3
View File
@@ -48,6 +48,12 @@ static const NSString * CSToastActivityViewKey = @"CSToastActivityViewKey";
static UIView *prevToast = NULL;
// doesn't matter these are static
static id commandDelegate;
static id callbackId;
static id msg;
static id data;
@interface UIView (ToastPrivate)
- (void)hideToast:(UIView *)toast;
@@ -56,12 +62,12 @@ static UIView *prevToast = NULL;
- (CGPoint)centerPointForPosition:(id)position withToast:(UIView *)toast withAddedPixelsY:(int) addPixelsY;
- (UIView *)viewForMessage:(NSString *)message title:(NSString *)title image:(UIImage *)image;
- (CGSize)sizeForString:(NSString *)string font:(UIFont *)font constrainedToSize:(CGSize)constrainedSize lineBreakMode:(NSLineBreakMode)lineBreakMode;
@end
@implementation UIView (Toast)
#pragma mark - Toast Methods
- (void)makeToast:(NSString *)message {
@@ -73,7 +79,11 @@ static UIView *prevToast = NULL;
[self showToast:toast duration:duration position:position];
}
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position addPixelsY:(int)addPixelsY {
- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position addPixelsY:(int)addPixelsY data:(NSDictionary*)_data commandDelegate:(id <CDVCommandDelegate>)_commandDelegate callbackId:(NSString *)_callbackId {
commandDelegate = _commandDelegate;
callbackId = _callbackId;
msg = message;
data = _data;
UIView *toast = [self viewForMessage:message title:nil image:nil];
[self showToast:toast duration:duration position:position addedPixelsY:addPixelsY];
}
@@ -101,12 +111,13 @@ static UIView *prevToast = NULL;
[self showToast:toast duration:CSToastDefaultDuration position:CSToastDefaultPosition addedPixelsY:0];
}
- (void)showToast:(UIView *)toast duration:(NSTimeInterval)duration position:(id)point addedPixelsY:(int) addPixelsY {
- (void)showToast:(UIView *)toast duration:(NSTimeInterval)duration position:(id)point addedPixelsY:(int) addPixelsY {
[self hideToast];
prevToast = toast;
toast.center = [self centerPointForPosition:point withToast:toast withAddedPixelsY:addPixelsY];
toast.alpha = 0.0;
// note that we changed this to be always true
if (CSToastHidesOnTap) {
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:toast action:@selector(handleToastTapped:)];
[toast addGestureRecognizer:recognizer];
@@ -168,6 +179,15 @@ static UIView *prevToast = NULL;
[timer invalidate];
[self hideToast:recognizer.view];
// also send an event back to JS
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:msg, @"message", @"touch", @"event", nil];
if (data != nil) {
[dict setObject:data forKey:@"data"];
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dict];
[commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
#pragma mark - Toast Activity Methods
+9 -1
View File
@@ -11,6 +11,7 @@
NSString *message = [options objectForKey:@"message"];
NSString *duration = [options objectForKey:@"duration"];
NSString *position = [options objectForKey:@"position"];
NSDictionary *data = [options objectForKey:@"data"];
NSNumber *addPixelsY = [options objectForKey:@"addPixelsY"];
if (![position isEqual: @"top"] && ![position isEqual: @"center"] && ![position isEqual: @"bottom"]) {
@@ -30,9 +31,16 @@
return;
}
[self.webView makeToast:message duration:durationInt position:position addPixelsY:addPixelsY == nil ? 0 : [addPixelsY intValue]];
[self.webView makeToast:message
duration:durationInt
position:position
addPixelsY:addPixelsY == nil ? 0 : [addPixelsY intValue]
data:data
commandDelegate:self.commandDelegate
callbackId:command.callbackId];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
pluginResult.keepCallback = [NSNumber numberWithBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}