Android: Let's talk about the Toast plot (BASICS) and androidtoast in Android apps.

Source: Internet
Author: User

Android: Let's talk about the Toast plot (BASICS) and androidtoast in Android apps.

Preface

Toast, a pretty girl who has been fascinated by thousands of software developers, especially android Developers, has always appeared frequently in various star applications. Toast is a magic horse ~ I heard it's a kind of toast. can you eat it? If the phone screen is made of chocolate, I think it tastes good. Let's get down to the truth. Let's talk about the Toast Application Scenario first. After all, Toast is also a person who has seen big scenes. Zhang sanzheng intends to take a wave on the mobile Internet, and suddenly Toast one: "The network is not powerful, I can't get the data"; Li Si wants to install the application to the memory card, then Toast one: "You can't even afford a memory card, and I can't find a place to install it." Wang Wu is tired of playing the game and wants to exit the application. When he exits, He Toast: "Come on, are you leaving? ". Therefore, since Toast has been widely applied in various streets and alleys, shouldn't we take a look at this Toast? Think about the excitement.

But now someone has to say that Toast is not easy? Direct

Toast. makeText (MainActivity. this, "Toast", Toast. LENGTH_LONG). show ();

It doesn't happen. Is there any good research? So, congratulations, you have mastered the most basic usage of Toast and have the knowledge to understand what you need next.

So the question is: what basic knowledge should we master Toast?

--------------------------------------- I am a splitting line (this blog is based on the basics and will publish two dry-goods Toast blogs later )--------------------------------------------

Common Toast

The so-called Wan Yi high floor from the ground up, D cover bust A cover; solid foundation, nothing. Case-driven, often better understood ~

One day, James cainiao received a job. The boss told him to show the unexpected places in the application (referring to network errors and misoperations) to the user, but he did not need to give back to the user. At this moment, James is full of confidence. Is this function perfect for Toast. Ctrl + c and ctrl + v code in the place required by the program. The code can be completed after three times, five times, and two times. Well, that's it.

Toast. makeText (MainActivity. this, "Toast", Toast. LENGTH_LONG). show ();

James is a newbie, but he is very studious. He not only fooled the code, but also studied the basic usage of Toast and summarized several articles:

1. Toast. makeText () returns the Toast instance. We can first obtain the Toast instance and then call the Show () method for display.

2. Toast does not occupy the focus, and does not block the subsequent Activity, causing it to change its lifecycle.

"Prompt User, Toast!" James wrote this rumor in his yellow notebook.

Move location for Toast

The next day, James tested the software with painstaking efforts and found that Toast often covered the user buttons that were located a little closer to the bottom from time to time. Although the trigger of the Button event was not affected, but it's awkward. No, so James read some of the gossip articles in the blog garden and finally found that he could use setGravity () to change the Toast display position! The code is released:

Toast toast = Toast.makeText(MainActivity.this, R.string.user_defined_location, Toast.LENGTH_LONG);toast.setGravity(Gravity.CENTER_VERTICAL, 0, -50);toast.show();

Finally, he pulled Toast to the center of the screen (Gravity. CENTER_VERTICAL), but James thought the center was not good. He moved up 50 distances in the vertical aspect, and the effect came out.

James certainly won't be able to solve this problem simply, so he also made a simple analysis of setGravity (gravity, xOffset, yOffset:

1. gravity is the position to be displayed by the input Toast, such as CENTER_VERTICAL (vertical center), CENTER_HORIZONTAL (horizontal center), TOP (TOP), and so on.

2. xOffset is the offset of Toast in the horizontal direction (X axis). The Offset Unit is greater than 0 to the right, and less than 0 to the left, 0 is not explained because Xiaoming is too lazy.

3. yOffset determines the Toast offset in the vertical direction (Y axis), which is greater than 0 to the downward offset and less than 0 to the upward offset. At the end, James adds a PS: It doesn't matter if he wants to set the Toast, anyway, Toast won't run out of the screen.

Add a Logo to Toast

When James used Toast, he thought she was old and monotonous. After reading it for a long time, he thought she was as beautiful as she was not pursuing her (except me !). Suddenly, I felt that I could add a Logo icon to Toast, so the question is: How can I achieve this? Du Niang is always a good teacher. James found such a piece of code:

Toast toast = Toast. makeText (MainActivity. this, R. string. user_defined_picture, Toast. LENGTH_LONG); LinearLayout toastView = (LinearLayout) toast. getView (); // get the LinearLayout of Toast. Note that the linear layout is ImageView image = new ImageView (MainActivity. this); image. setImageResource (R. drawable. ic_launcher); // generates the ImageViewtoastView of a realistic Logo. addView (image); // load the ImageView to the LinearLayout top toast. show ();

James happy copied the code into the project, which showed the effect:

Call (~ O ~)~ ZZ... James noticed that the comment emphasizes linear layout. Why? Since this blog is mainly about the basics, I will not analyze the source code here. I just want to emphasize that the layout of Toast in the source code uses LinearLayout, so when you get the view, you can consciously turn it into a linear layout.

Create a Toast

James found another setView () method in the process of adding Logo to Toast. Well, since getView () is used to get the Toast layout, according to James's ideas, setView () is undoubtedly set the Toast layout. "If it's not even true, it's just like watching live!" James said that since he discovered this magical stuff, James thought it would be better to add a Logo to complete customization. There are several times of travel in your life, and the Code cannot be a few times of passion.

Toast custom code:

Toast toast = Toast.makeText(MainActivity.this, R.string.user_defined_picture, Toast.LENGTH_LONG);LinearLayout toastView = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.toast_view, null);toast.setView(toastView);toast.show();

The xml layout file is simple:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical" >        <TextView             android:layout_height="wrap_content"            android:layout_width="wrap_content"            android:text="@string/user_defined_all"            />        <ProgressBar             android:layout_width="wrap_content"            android:layout_height="wrap_content"            /></LinearLayout>

The results are as follows:

Tian You James escaped the fate of the live broadcast. in James's expectation, a temporary custom Toast came into being.

The camera turned to James and smiled: "Haha ~".

Run Toast Asynchronously

A few days later, James encountered a big problem. He needed to display Toast after clicking a certain time, that is, to asynchronously execute Toast. show (). James first created a new Thread subthread and called Toast. show () after the specified time (). However, Logcat provides a lot of Red Cross forks and returns an error !!!! This can be noted down. Since Toast will report an error by enabling the subthread, the question is: how can we complete the task on demand?

Method 1: Since an error is reported in the sub-thread, Handler is used to execute it in the message queue.

handler.post(new Runnable() {  @Override  public void run() {    Toast.makeText(MainActivity.this, R.string.other_thread, Toast.LENGTH_LONG).show();
  }});

PS: This Runnable executes run in the main thread. For details, see the Google documentation. Therefore, no error is reported.

Method 2: We can forcibly execute the statement in the Child thread. We only need to obtain the logoff.

New Thread () {@ Override public void run () {Looper. prepare (); Toast. makeText (MainActivity. this, R. string. other_thread, Toast. LENGTH_LONG ). show (); logoff. loop (); Log. I ("text", "NOTE: logoff. the code after loop () will not be executed "); // LogCat no output}
}. Start ();

There is nothing to explain about the asynchronous running of Toast. However, in the next advanced blog to analyze Toast, We need to master this to better customize the Toast we need.

 

If you think you can write well, click like n (* too many threads *) n ...... Thank you for taking the time to read this basic blog.

 

By enjoy wind chimes
Source:Http://www.cnblogs.com/net168/
The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and provide a connection to the original article clearly on the article page. Otherwise, you will not be reposted next time.


How to Use Toast in Android

. Micro-studios.com1. Default display mode

How to Use Toast in Android

My current setting is centered on the top of the top ???????????????? // The second parameter: Set the offset of the horizontal X axis at the toast position relative to the first parameter. The positive value is offset to the right, the negative number is shifted to the left offset ???????????????? // The third parameter: The same as the second parameter ???????????????? // If the offset you set exceeds the screen range, toast will be displayed near the exceeded boundary in the screen ???????????????? Toast. setGravity (Gravity. TOP | Gravity. CENTER,-50,100 );?????????????????? // The screen is centered. The offset between the X axis and Y axis is 0 ???????????????? // Toast. setGravity (Gravity. CENTER, 0, 0 );???????????????? Toast. show ();???? 3. java code Toast toast = Toast with images. makeText (getApplicationContext (), "display toast with image", 3000 );???????????????? Toast. setGravity (Gravity. CENTER, 0, 0 );?????????????????? // Create an image view object ???????????????? ImageView imageView = new ImageView (getApplicationContext ());???????????????? // Set the image ???????????????? ImageView. setImageResource (R. drawable. ic_launcher );???????????????? // Obtain the toast Layout ???????????????? LinearLayout toastView = (LinearLayout) toast. getView ();???????????????? // Set the layout to horizontal ???????????????? ToastView. setOrientation (LinearLayout. HORIZONTAL );???????????????? // Add the ImageView to the first position in this layout ???????????????? ToastView. addView (imageView, 0 );???????????????? Toast. show ();???? 4. Fully custom display method Java code // Inflater means inflatable ?????????????? // LayoutInflater class is used to instantiate the layout of an XML file to its corresponding view object ?????????????? LayoutInflater inflater = getLayoutInflater ();?????????????? // Fill in a view object ?????????????? View layout = inflater. inflate (R. layout. custom2, (ViewGroup) findViewById (R. id. llToast ));?????????????????????????????? ImageView image = (ImageView) layout. fi ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.