display toast in android example
Hello Guys. Welcome to our new tutorial of display toast in android example. android toast mostly use to display any information of message for a short period of time and disappears after some time.
please follow the code given below to display the android toast activity.
- First Create a new project in Android Studio
- File ⇒ New Android ⇒ Application Project
- Then Open src -> package -> MainActivity.java and then add following code :
JAVA (MainActivity.java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class ToastActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_toast); Button btn = (Button)findViewById(R.id.toast); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ToastActivity.this, "Button Clicked.", Toast.LENGTH_SHORT).show(); } }); } } |
- Now Open res -> layout -> activity_main.xml and then add following code :
XML (activity_main.xml)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/toast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:layout_marginTop="200dp" android:layout_marginLeft="140dp"/> </LinearLayout> |
Output:
Finally, run this project.
This is how Android toast application looks like. this is the basic toast. also, I will tell you how to create custom toast in the next article.