Reputation: 21178
I have a Toast message I use as a splash screen which I would like to add a callback to once it closes. How is this achievable in Android?
// Splash
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.splash, (ViewGroup) findViewById(R.id.frameLayout1));
layout.setBackgroundColor(Color.WHITE);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Upvotes: 3
Views: 2218
Reputation: 191
In Android 11 (API 30) they've added a method doing exactly that: Toast.addCallback(Toast.Callback) So I would do smth like this:
fun showToastAndProceedWith(message: String, isLengthShort: Boolean, actionToFollow: () -> Unit) {
val toastLength = if (isLengthShort) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
Toast.makeText(this, message, toastLength).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
addCallback(object : Toast.Callback() {
override fun onToastShown() {
//empty
}
override fun onToastHidden() {
actionToFollow.invoke() // or you could use another action
}
})
} else {
val delayMs = if (isLengthShort) 2000L else 3500L
Handler(Looper.getMainLooper()).postDelayed(actionToFollow, delayMs)
}
show()
}
}
Upvotes: 0
Reputation: 5212
I didn't test this but you might be able to add a visibilitychanged listener to the view that you pass to the toast, refer to http://developer.android.com/reference/android/view/View.html#onWindowVisibilityChanged(int)
Alternatively, you could set a timer using the toast duration fetched by getDuration()
Is there a reason you are using a toast for this? Why not updating the view using setview after a defined period of time or using a seperate Activity?
Upvotes: 2