The default Toast for Android is very simple and easy to use. However, sometimes our program uses the default Toast instead of the overall style of the program. In this case, we need to customize Toast to make it more integrated with our program.
To use custom Toast, first we need to add a layout file. The structure of the layout file is the same as that used by the Activity. In this layout file, we need to design the Toast layout, for example:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>
Note that the id attribute we added to LinearLayout must be used in subsequent code. In the program, we can use the following code to create our own Toast:
Public class MainActivity extends Activity {private Button btn; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); btn = (Button) findViewById (R. id. btn); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// get the LayoutInflater object, this object can convert the XML file to the View object LayoutInflater inflater = getLayoutInflater (); // create a hierarchical View object based on the specified layout file // The second parameter is the root node of the View object, that is, the ID View layout = inflater of LinearLayout. inflate (R. layout. toast_layout, (ViewGroup) findViewById (R. id. toast_layout_root); // you can find the ImageView control. // you can find the ImageView image = (ImageView) layout in layout. findViewById (R. id. image); image. setImageResource (R. drawable. head); TextView text = (TextView) layout. findViewById (R. id. text); text. setText ("Custom Toast Demo"); Toast toast = new Toast (getApplicationContext (); // set Toast position toast. setGravity (Gravity. CENTER_VERTICAL, 0, 0); toast. setDuration (Toast. LENGTH_LONG); // display Toast as custom toast. setView (layout); toast. show ();}});}}
Running effect: