class MainActivity : AppCompatActivity() {
private lateinit var trueButton : Button;
private lateinit var falseButton : Button;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
trueButton=findViewById(R.id.true_button)
falseButton=findViewById(R.id.false_button)
trueButton.setOnClickListener { view: View ->
val myToast1=Toast.makeText(this,R.string.correct_toast,Toast.LENGTH_SHORT)
myToast1.setGravity(Gravity.TOP,0,0)
myToast1.show()}
falseButton.setOnClickListener { view: View ->
val myToast2=Toast.makeText(this,R.string.incorrect_toast,Toast.LENGTH_SHORT)
myToast2.setGravity(Gravity.TOP,0,0)
myToast2.show()}
}
}
It SHOULD work, but in the emulator, the toast still shows up in the default position (bottom of the screen). I’ve tried other people’s solutions too and those don’t seem work for me either. What am I doing wrong?
I’ve tried using setText() on the toast and that works just fine, but setGravity() doesn’t
The default virtual device is the Pixel 3a, running Android API 30 (R), that’s why setGravity has no effect (is no-op).
My recommendation is to go back some pages and create the virtual device as the book teaches, running Android API 28 (Pie).
It works in your device probably because it’s still running Android Q, at the most.
Thanks for posting this. I had the same solution and the same problem! It works on my physical phone. It’s a relatively new phone. I also saw the warning on the developer.android site. I’m a little unclear on its meaning. What would be the alternative solution when running a newer virtual device?
I also saw the warning on the developer.android site. Thanks for brining it up. I’m a little unclear on the message’s meaning. What would be an alternative solution when running a newer virtual device?
SnackBar is different than Toast in relation to positioning… you have to create the area that you want to display the Snackbar in it within the view and use it on the code
I did this as a small example if you want to display the Snackbar at the top
this is the view file, i added a coordinated widget and a button within a constrained layout