The default location for toast in Android is located near the bottom of the screen, which is sometimes inappropriate. For example, when there is less content on the page, the content is generally centered on the upper half of the screen, and the user's attention is focused on the upper half of the screen, and toast users in the default location may not notice. There may also be a default location where the toast is blocked by the user's hand. In practice, it is better to show toast in the middle or upper center of the screen. How do I change the default location for toast? Here is a simple example to illustrate.
First on:
The layout file Activity_toast.xml code is as follows:
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" > <ButtonAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:onclick= "Onclickdefaulttoast"Android:text= "Click on toast to show default location" /> <ButtonAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:onclick= "Onclickcentertoast"Android:text= "Tap to show toast at center position" /> <ButtonAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:onclick= "Onclicktoptoast"Android:text= "Click to show toast at the top of the center" /></LinearLayout>
The background Toastactivity.java code is as follows:
PackageChengyujia.demo.aty;ImportAndroid.os.Bundle;ImportAndroid.view.Display;Importandroid.view.Gravity;ImportAndroid.view.View;ImportAndroid.widget.Toast;ImportCHENGYUJIA.DEMO.R; Public classToastactivityextendsbaseactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_toast); } Public voidOnclickdefaulttoast (View v) {Toast.maketext ( This, "Toast at default location", Toast.length_long). Show (); } Public voidOnclickcentertoast (View v) {Toast Toast= Toast.maketext ( This, "center-position Toast", Toast.length_long); Toast.setgravity (Gravity.center,0, 0); Toast.show (); } Public voidOnclicktoptoast (View v) {display display=Getwindowmanager (). Getdefaultdisplay (); //Get screen height intHeight =display.getheight (); Toast Toast= Toast.maketext ( This, "center toast at Upper position", Toast.length_long); //Here's a y-axis offset for a 1/4 screen height.Toast.setgravity (gravity.top, 0, HEIGHT/4); Toast.show (); }}
Android changes the default location for Toast