Android Basic Tools Class refactoring Series A toast

Source: Internet
Author: User
Tags getcolor

Objective:

have been thinking about writing some of the actual Android project summary, look at the CSDN blog, the previous article has been more than a year.

This series locates Android Basic Tool class refactoring. It is designed to document some of the commonly used tool classes in real projects, such as Toast, Dialog, animation classes, Imageloader classes, and so on. Is combing, but found that after combing the expected yellow vegetables are cold. So change the strategy, write the side to comb.

The first thing to write is this toast.

I. Description

As the base class provided by the Android system, toast is the simplest hint message class. Features suspension. Voluntarily destroy itself within a specific time span of the interface (Activity).

Second, simple use

Toast.maketext (Getapplicationcontext (), "You want to cue the message", Toast.length_short). Show ();

In particular: Viewing the source code finds that the Maketext method returns a toast instance, such as the following:

// because a new toast will be made each time, which is why it is assumed that multiple calls to Maketext at the same time will pop up several prompt boxes. Until all of the tips are complete before they disappear.

Source:

  public static Toast Maketext (context context, charsequence text, @Duration int Duration) {        toast result = new Toast (CO ntext);        Layoutinflater inflate = (layoutinflater)                context.getsystemservice (context.layout_inflater_service);        View v = inflate.inflate (com.android.internal.r.layout.transient_notification, null);        TextView TV = (TextView) V.findviewbyid (com.android.internal.r.id.message);        Tv.settext (text);                Result.mnextview = V;        result.mduration = Duration;        return result;    }


Third, complex use

We see the source code. The layout component is used. That means we can also define our own view,toast to provide the display position on the screen.

This allows us to define our own style of toast and display it in the required position. See Four

Iv. use in actual projects

4.1, relevant knowledge points

1) The Toast style is consistent in the actual project, meaning that only one toast instance is needed throughout the app life cycle to

2) The context used in the toast can be used directly in the context of the appliction.

Because the number of context in the app = number of 1 application + n*activity + m*service

4.2. Problems to be encountered

Avoid repeatedly popping toasts as described above, so we will infer whether a toast instance exists, assuming that there is a direct use. If it doesn't exist, it's new.

4.3. Effect

This example uses a toast that pops up at the top of the interface. If the green cue bar successfully pops up, the yellow cue bar fails

4.4, words not much said, on the code

Package Com.ray.utils;import Android.content.context;import Android.content.res.resources;import Android.os.handler;import Android.view.gravity;import Android.view.layoutinflater;import Android.view.View;import Android.widget.textview;import Android.widget.toast;import Com.ray.r;import com.ray.app.utils.applicationutil;/** * User:ray * DATE:16/3/3 * readme:toast-tools */public class Toastutil {private static context context = Baseapplicat Ion.getinstance ();//The only context in the app life cycle. Baseapplication inherit application private static Layoutinflater Inflater = Layoutinflater.from (context);//Layout loading private s    Tatic View Mytoastview = inflater.inflate (r.layout.layout_top_toast, NULL);    private static TextView Msgview = (TextView) Mytoastview.findviewbyid (R.id.tv_msg_text);    private static final int type_code_success = 0x01;    private static final int type_code_error = 0x02;    private static final int color_success = Context.getresources (). GetColor (r.color.msg_status_success); Private Static final int color_error = Context.getresources (). GetColor (R.color.msg_status_warn);  private static final int default_time_delay = 50;//Unit: Ms private static Toast toast;//system hint class private static Handler    Handler        public static void showsuccessmsg (int msgresid) {try {showsuccessmsg (context.getstring (MSGRESID));        } catch (Resources.notfoundexception e) {e.printstacktrace (); }} public static void showerrormsg (int msgresid) {try {showerrormsg (context.getstring (MSGRESID)        );        } catch (Resources.notfoundexception e) {e.printstacktrace ();    }} public static void Showsuccessmsg (String msg) {showmsg (type_code_success, msg);    } public static void Showerrormsg (String msg) {showmsg (Type_code_error, msg); } private static void ShowMsg (final int typecode, final String msg) {if (context = = null//| |!a Pplicationutil.isrunningforeground (ConteXT)//If the app returns to the background, does not display | |        msg = = null) {return;        } if (toast = = null) {//Prevent repeated prompts: Not NULL, that is, global use of the same toast instance toast = new Toast (context);        } if (handler = = null) {handler = new handler (); } handler.postdelayed (New Runnable () {@Override public void run () {int Msgvi                Ewbagcolor = 0;                        Switch (typecode) {case type_code_success:msgviewbagcolor = color_success;                    Break                        Case type_code_error:msgviewbagcolor = Color_error;                    Break                        Default:msgviewbagcolor = color_success;                Break                } msgview.setbackgroundcolor (Msgviewbagcolor);                Msgview.settext (msg);                Toast.setview (Mytoastview); Toast.setgravity (Gravity. TOP |                Gravity.fill_horizontal, 0, 0);//top Center toast.setduration (toast.length_short);            Toast.show ();    }}, Default_time_delay); }//temporarily incorrect provision: primary for need at some point, to cancel the prompt private static void Canceltoast () {if (toast! = null) {Toast.cance            L ();        toast = null; }    }}

<?xml version= "1.0" encoding= "Utf-8"?

><relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= " Match_parent " android:layout_height=" wrap_content " android:clickable=" false " android:focusable=" False "> <textview android:id=" @+id/tv_msg_text " android:layout_width=" Match_parent " android:layout_height= "@dimen/nav_height" android:background= "@color/msg_status_success" android: Ellipsize= "End" android:gravity= "center" android:maxlines= "2" android:paddingleft= "15DP " android:paddingright= "15DP" android:textcolor= "@color/white" android:textsize= "16DP"/></ Relativelayout>

V. Android5.0 official New Replacement components

There is not much use on the market at the moment, perhaps.

。。

Android Basic Tools Class refactoring Series A toast

Related Article

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.