Home Next Tutorial

How To Display Message on Button Click in Android


Step 1: Open Android Studio
Step 2: Select File->New->New Project
Step 3: In the Create New Project window type Application Name as "ToastTutorial" and click on Next button. In the Target Android Devices select Minimum SDK and click on Next Button. In The Add an Activity to Mobile select blank activity and click on Next Button.Click on Finish button.
Step 4: Design an activity as shown below:

Toast Example

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:id="@+id/btnClick"

android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="164dp" />
</RelativeLayout>

Step 5: Open MainActivity.java file and write following code in onCreate method

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.btnClick);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),"Button Clicked",Toast.LENGTH_LONG).show();
}
});
}

Step 6:Run the application. It will display output as shown below:

Toast Example

Download Projects


Download Programs