Android Toast Example
Toast can be used to display information for the short period of time. You can also create custom toast such as toast displaying image etc.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.
Constants of Toast class
- public static final int LENGTH_LONG
- public static final int LENGTH_SHORT
Methods of Toast class
- public static Toast makeText(Context context, CharSequence text, int duration)
- public void show ()
- public void setMargin (float horizontalMargin, float verticalMargin)
Simple example to display the toast
- Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
Another code:
- Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT);
- toast.setMargin(50,50);
- toast.show();
Here, getApplicationContext() method returns the instance of Context.
Full code of Activity class
Let's see the code to display the toast.
File: MainActivity.java
- package com.example.toast;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.View;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //Displaying Toast with Hello Javatpoint message
- Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
No comments:
Post a Comment
any queries pls tel me