Android Basics – Add a Button and display a Toast on click

Time for some Action. Let’s add a Button to the Layout XML file and on click of button let’s display a message to the user.

Simple Steps

Add a Button component to the XML file.

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/buttonId"
    android:text="Click Me"
    android:onClick="clickMe"
    android:layout_margin="15dp"/>



Add a method to the MainActivity class.

public void clickMe(View view){
    Toast.makeText(MainActivity.this, "Button Clicked !!", Toast.LENGTH_SHORT).show();
}

You are all set. Test your app now.

Source Code  

https://github.com/ankur-srivastava/HelloAndroid/tree/master/app/src/main/java/com/edocent/helloandroid

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s