My applications have a Toast. But if the soft keyboard is displayed the Toast sort of merged with the soft keyboard and is hard to distinguish. So I looked up how to set a custom view to a Toast. But the View property (SetView and GetView methods) is deprecated.
Instead I was told to use a Snackbar.
I have managed to create a Snackbar with a custom view. I have these problems:
The Snackbar's position is in the lower left corner of my app.
I would like to display the Snackbar as a Toast is displayed:- At the bottom and in the middle of the screen.
- Some distance between the Snackbar's bottom and the screen's bottom.
- At the bottom and in the middle of the screen.
The Snackbar is displayed behind the soft keyboard.
I would like to display the Snackbar above the soft keyboard.
I can hide the soft keyboard to show the Snackbar. But I would prefer not to hide it.
I have googled a lot on these two problems, but have not found any solutions.
For problem #1 I have tried
- How can you adjust Android SnackBar to a specific position on screen
- I was not able to get the
CoordinatorLayout
to compile. - Setting the margin on a Layout didn't work.
- I was not able to get the
For problem #2 I have tried
- Show Android SnackBar above keyboard? but it didn't work.
Here is my code:
res/layout/snackbar.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView style="@style/SomeStyle"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/tvSnackbarText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Snackbar" />
Fragment
private fun showSnackbarMessage(message: String) {
val view: View = LayoutInflater
.from(context)
.inflate(R.layout.snackbar, null)
val tvSnackbarText = view.findViewById<TextView>(R.id.tvSnackbarText)
tvSnackbarText.text = message
tvSnackbarText.gravity = Gravity.CENTER
val snackbar = Snackbar.make(requireView(), "", Snackbar.LENGTH_LONG)
snackbar.view.setBackgroundResource(R.drawable.rounded_corner_box_grey_stroke);
val params = snackbar.view.layoutParams as FrameLayout.LayoutParams
params.height = FrameLayout.LayoutParams.WRAP_CONTENT
params.width = FrameLayout.LayoutParams.WRAP_CONTENT
snackbar.view.layoutParams = params
val layout = snackbar.view as Snackbar.SnackbarLayout
layout.addView(view)
snackbar.show()
}