Toast on button click-AGN HUB

 To show a Toast message on a button click in Android using Kotlin, follow these steps:

Steps:

  1. Add a Button in the Layout XML: Define a Button in your activity_main.xml file.

  2. <Button

  3.     android:id="@+id/buttonToast"

  4.     android:layout_width="wrap_content"

  5.     android:layout_height="wrap_content"

  6.     android:text="Show Toast"

  7.     android:layout_gravity="center" />

  8. Handle the Button Click in the Kotlin File: In your activity file (e.g., MainActivity.kt), set a click listener for the button to display the Toast.

  9. import android.os.Bundle

  10. import android.widget.Button

  11. import android.widget.Toast

  12. import androidx.appcompat.app.AppCompatActivity


  13. class MainActivity : AppCompatActivity() {

  14.     override fun onCreate(savedInstanceState: Bundle?) {

  15.         super.onCreate(savedInstanceState)

  16.         setContentView(R.layout.activity_main)


  17.         // Find the button

  18.         val buttonToast: Button = findViewById(R.id.buttonToast)


  19.         // Set a click listener

  20.         buttonToast.setOnClickListener {

  21.             Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()

  22.         }

  23.     }

  24. }

Explanation:

  • findViewById: Locates the button in the layout.

  • setOnClickListener: Assigns a click event listener to the button.

  • Toast.makeText: Creates and shows the toast message. Parameters: 

    • this: The context.

    • "Button Clicked!": The message to display.

    • Toast.LENGTH_SHORT: Duration of the toast (short or long).

Result:

When you click the button, a Toast message saying "Button Clicked!" will appear briefly on the screen.

Comments

Popular posts from this blog

RadioButtons-AGN HUB

Checkbox- AGN HUB

Timepicker- AGN HUB