Show Toast above keyboard
You can change toast postion by following code.
Toast toast= Toast.makeText(getApplicationContext(),
"Your string here", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
More than 3 years later... and Android has finally an API
As shown detailed by Chris Banes we now can use the WindowInsets
API
The core API to solve a Toast above soft keyboard are:
val insets = ViewCompat.getRootWindowInsets(view) // get insets
val imeVisible = insets.isVisible(Type.ime()) // is keyboard visible?
val imeHeight = insets.getInsets(Type.ime()).bottom // voila, your offset
So I build an extension function to Toast:
/**
* Shows toast above soft keyboard, if exists
*/
fun Toast.showAboveKeyboard(containerView: View) {
// get y offset to let toast appear above soft keyboard
val insets = ViewCompat.getRootWindowInsets(containerView)
val imeVisible = insets?.isVisible(WindowInsetsCompat.Type.ime()) ?: false
val imeHeight = insets?.getInsets(WindowInsetsCompat.Type.ime())?.bottom
val fallbackYOffset = containerView.resources.getDimensionPixelOffset(R.dimen.thirtytwo_grid_unit)
val noSoftKeyboardYOffset =
containerView.resources.getDimensionPixelOffset(R.dimen.three_grid_unit)
setGravity(
Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM,
0,
if (imeVisible) imeHeight ?: fallbackYOffset else noSoftKeyboardYOffset
)
show()
}
Usage in a fragment:
Toast.makeText(requireContext(), "Hello Toast", Toast.LENGTH_SHORT)
.showAboveKeyboard(requireView())
Happy Toast!