Toast on button click-AGN HUB
To show a Toast message on a button click in Android using Kotlin, follow these steps:
Steps:
Add a Button in the Layout XML: Define a Button in your activity_main.xml file.
<Button
android:id="@+id/buttonToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
android:layout_gravity="center" />
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.
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Find the button
val buttonToast: Button = findViewById(R.id.buttonToast)
// Set a click listener
buttonToast.setOnClickListener {
Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()
}
}
}
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
Post a Comment