How to show Toast on Button Click | Android Studio 2.2.1 Tutorial



A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.




Sample Toast Preview



How to do ?

Add a button in activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@android:color/white"
tools:context="com.sabithpkcmnr.toast.MainActivity">
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click to Toast"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>



MainActivity


 package com.sabithpkcmnr.toast;  

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn = (Button) findViewById(R.id.bt);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Here is my Toast Text",Toast.LENGTH_LONG).show();
}
});

}
}
we had shown the Toast programmatically in MainActivity


That's it.
Thanks for your time

No comments:

Powered by Blogger.