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:Copy codeThe Code is as follows: <? 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:Copy codeThe Code is as follows: 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)
{
// Obtain the LayoutInflater object, which can convert the XML file into a 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 LinearLayout ID.
View layout = inflater. inflate (R. layout. toast_layout, (ViewGroup) findViewById (R. id. toast_layout_root ));
// Search for the ImageView Control
// Note: Search in layout
ImageView image = (ImageView) 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 the Toast location
Toast. setGravity (Gravity. CENTER_VERTICAL, 0, 0 );
Toast. setDuration (Toast. LENGTH_LONG );
// Display Toast as custom
Toast. setView (layout );
Toast. show ();
}
});
}
}
Running effect:
You do not understand the world of the arms, you do not know the life of the arms, and you only know the world of programmers. Programmers, strive for their own wonderful world, and work hard! Come on ......