GeoQuiz Challenge 1: Toast Gravity doesn't change

This is my solution for challenge 1:

class MainActivity : AppCompatActivity() {
    private lateinit var trueButton : Button;
    private lateinit var falseButton : Button;
    override fun onCreate(savedInstanceState: Bundle?) {

        trueButton.setOnClickListener { view: View ->
            val myToast1=Toast.makeText(this,R.string.correct_toast,Toast.LENGTH_SHORT)
        falseButton.setOnClickListener { view: View ->
            val myToast2=Toast.makeText(this,R.string.incorrect_toast,Toast.LENGTH_SHORT)

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

Solved! (kinda)
While the virtual device (pixel 3a) refused to show the toast anywhere else, I’ve tried it on my physical OnePlus5 and it works now.

I stumbled on this also. Check this:

It states

Warning: Starting from Android Build.VERSION_CODES#R , for apps targeting API level Build.VERSION_CODES#R or higher, this method is a no-op when called on text toasts.

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 the answer, I’ll either use an older API then, or avoid using virtual device entirely. (I always have my phone with me anyway)

1 Like