2

I am creating a simple app on which when the button is clicked a toast message is displaying. But when the button is clicked the toast message does not display.

This is my mainActivity and activityMain.xml code.

package com.example.myapplication2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val clickMeButton = findViewById<Button>(R.id.toast_button)

        clickMeButton.setOnClickListener {
            Toast.makeText(applicationContext, "Toast Message", Toast.LENGTH_LONG).show()
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/toast_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Lino
  • 5,084
  • 3
  • 21
  • 39

1 Answers1

1

You should use activity context but you are using appcontext (see Difference between Activity Context and Application Context). You should update code with this:

Toast.makeText(this, "Toast Message", Toast.LENGTH_LONG).show()
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Yasin Ege
  • 605
  • 4
  • 14