Cancel an already open toast in Android

I am currently starting to develop Android applications, and I am tracking this tutorial on how to use and improve the Google Maps app.

I managed to display a map on the screen, by touching I get the location address (via reverse geocoding) with the Toast display. But here is my problem - when you click on the map several times in a row, you will get all toasts one by one, and each of them will take its time (in my case - Toast.LENGTH_LONG ) to disappear. I want the application to automatically close the old toast and show a new toast with a new address.

In other resources, I found that I should use the toast.cancel() method for this purpose, but I am having problems using it - I have already redefined onTouchEvent - how can I detect that there is a new touch over the map, while Toast shows? Or maybe you would suggest me a better way to hide the already open Toast ?

I tried to make my Toast address global, but it didn't work either.

Here is my application code:

 @Override public boolean onTouchEvent(MotionEvent event, MapView mapView) { //---when user lifts his finger--- if (event.getAction() == 1) { GeoPoint p2 = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY()); Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocation(p2.getLatitudeE6() / 1E6, p2.getLongitudeE6() / 1E6, 1); String add = " "; if (addresses.size() > 0) for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++) add += addresses.get(0).getAddressLine(i) + "\n"; Toast address; address = Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG); address.show(); } catch (IOException e) { e.printStackTrace(); } return true; } return false; } 
+8
android google-maps toast
Jul 19 '11 at 8:14
source share
2 answers

You do not show where your Toast address is global, but each time you click, you create a new local Toast object:

 Toast address; address = Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG); address.show(); 

Which will override the global object you create. I would recommend having address as a private static object in your class, to ensure that the address will always be the same object no matter how many times you click, so that you always cancel the Toast that you last showed (starting with exists only one) and delete the local declaration:

 private static Toast address; 

...

 if (address != null) address.cancel(); address = Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG); address.show(); 
+22
Jul 19 '11 at 8:24
source share

You need to get an instance when creating Toast by calling make (). After that, before you show the new toast, you must cancel the old Toast.GoodLuck!

+1
Jul 19 '11 at 8:25
source share



All Articles