Here is source code of the Program to Demonstrate Custom Toast in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.
A toast lets a user to show a quick and little message on the screen , u can show a toast by using the Android built in toast or create a toast on your own using the Toast class in Android , the following given code makes a toast to be shown on screen and also display the toast in the center of the screen using Toast.Gravity set method.
Main Activity
package com.example.custom_toast; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button click = (Button)findViewById(R.id.button1); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.custom_toast_layout)); text.setText("Custom Toast in Center of Screen"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Toast_Layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#DAAA" android:orientation="horizontal" android:padding="8dp" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/black" /> </LinearLayout>
advertisement
Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.
If you wish to look at all Tutorials, go to Java Android Tutorials.
Related Posts:
- Apply for Java Internship
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Practice BCA MCQs
- Check Java Books