Toast is more commonly used to display short reminders, such as disconnection of the network connection.
Simple code instance of toast
findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override publicvoidonClick(View v) { // TODO Auto-generated method stub //核心代码 Toast.makeText(MainActivity.this"显示Toast", Toast.LENGTH_LONG).show(); } });
The first parameter of Maketext is the context, the second parameter is the displayed message, the third is the length of time displayed, there are two options, this article is longer, and the other is toast.length_short.
Set the location of a toast
findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override publicvoidonClick(View v) { // TODO Auto-generated method stub Toast toast = Toast.makeText(MainActivity.this"显示Toast", Toast.LENGTH_SHORT); //关键代码 00); toast.show(); } });
Toast.setgravity (gravity.center, 0, 0); three parameters of this function, the first parameter sets the position of the toast with the Gravity constant, the second is the x-axis offset, the positive value is the right, the third is the y-axis offset, and the positive value is down.
Set up a toast for a complex layout
Instance code:
Findviewbyid (R. ID. Button1). Setonclicklistener(New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto-generat Ed method stub Toast Imagetoast = Toast. Maketext(mainactivity. this,"Show Toast", Toast. LENGTH_short);Imagetoast. Setgravity(Gravity. CENTER,0,0);ImageView image = new ImageView (mainactivity. this);Image. Setimageresource(R. ID. Icon);Imagetoast. Setview(image);Imagetoast. Show();} });
Attention:
After setting up the picture, the original message cannot be displayed, so if you want to set up multiple components you can create a new layout such as LinearLayout. Use this method to display Imagetoast.setview (image);
Android Toast Tutorial-android Learning Journey (i)