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?) {
        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

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:
https://developer.android.com/reference/kotlin/android/widget/Toast#setgravity

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.

2 Likes

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