I'm currently starting to develop Android applications and I've been following up a this tutorial on how to use and improve the Google maps application.
I've managed to show up on screen the map, on touch I get the address of a location (via Reverse Geocoding) with the showing of a Toast
. But here is my problem - when you click a number of consecutive times over the map you will get all the toasts
one after other and each of them will take his time (in my case - Toast.LENGTH_LONG
) to disappear. I want to make the application automatically close the older toast and show a new toast with the new address clicked.
In other resources I found I should use the toast.cancel()
method for this purpose, but I experience trouble using it - I have already overrided the onTouchEvent
- how can I detect there is a new touch over the map while the toast
is showing?
Or maybe you would suggest me a better way of hiding the already open toast
?
I've tried to make my Toast
address a global one, but it wasn't working also.
Here is my code for the application:
@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;
}
You don't show where you have Toast address
as a global, but you are creating a new, local Toast object each time you click with:
Toast address;
address = Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG);
address.show();
Which will override the global object you are creating. I'd recommend having address
as a private static
object in your class to ensure that address will always be the same object no matter how many times you click so that you are always cancelling the Toast
that you last showed (since there is only ever one), and remove the local declaration:
private static Toast address;
...
if (address != null)
address.cancel();
address = Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG);
address.show();
You need to get instance when create Toast by call make().After that before you show new toast, you should cancel old Toast.GoodLuck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With