Android --- 59 --- use of Toast and use of toast in android
Originally, Toast had only one simple function, namely Toast. makeText (context, text, duration). show.
But a problem I found a few days ago is that it cannot be used in the child thread, so I looked at the Toast usage. Toast can also be displayed in custom positions, images, and sub-threads.
Example:
Layout file:
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = "com. example. toasttest. mainActivity "> <Button android: id =" @ + id/bt1 "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: text = "default"/> <Button android: id = "@ + id/bt2" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Custom display location"/> <Button android: id = "@ + id/bt3" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "with image"/> <Button android: id = "@ + id/bt4" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "in other threads"/> </LinearLayout>
Activity:
Public class MainActivity extends Activity implements OnClickListener {Button bt1, bt2, bt3, bt4, bt5; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bt1 = (Button) findViewById (R. id. bt1); bt2 = (Button) findViewById (R. id. bt2); bt3 = (Button) findViewById (R. id. bt3); bt4 = (Button) findViewById (R. id. bt4); listener (this); bt2.setOnClickListener (this); bt3.setOnClickListener (this); bt4.setOnClickListener (this);} @ Overridepublic void onClick (View v) {Toast toast; switch (v. getId () {case R. id. bt1: // Toast is displayed by default. makeText (MainActivity. this, "Default display", 1 ). show (); break; case R. id. bt2: // custom display position toast = Toast. makeText (MainActivity. this, "Custom display position", 1); toast. setGravity (Gravity. TOP, 0, 0); toast. show (); break; case R. id. bt3: // toast = Toast. makeText (MainActivity. this, "with image display", 1); toast. setGravity (Gravity. CENTER, 0, 0); LinearLayout toastView = (LinearLayout) toast. getView (); ImageView imageView = new ImageView (getApplicationContext (); imageView. setImageResource (R. drawable. pig); toastView. addView (imageView); toast. show (); break; case R. id. bt4: // display new Thread (new Runnable () {@ Overridepublic void run () {loid. prepare (); Toast. makeText (MainActivity. this, "using Toast in thread", 1 ). show (); logoff. loop ();}}). start (); break; default: break ;}}}