Android self-defined toast

Source: Internet
Author: User

First, Introduction

In the process of development you will find that there are many limitations to the toast tips of Android itself, such as I want to define the animation of the toast myself, define an aesthetically pleasing view to display in the toast, and many others to let the toast show the specified length and so on.

First of all, how it works:



Second, the principle

The principle of self-definition is also very easy, is to add view and delete view WindowManager, just need to set the style of windowmanager.layoutparams and view. Make it look very similar to the toast of the Android system.

Detailed code such as the following:

/** * Custom Toast * * @author Lucky * */public class Toasthelper {public static final int length_long = 3500;public STA Tic Final int length_short = 2000;private WindowManager mwindowmanager;private windowmanager.layoutparams mWindowParams ;p rivate View toastview;private Context mcontext;private Handler mhandler;private String mtoastcontent = "";p rivate int du ration = 0;private int animstyleid = Android. R.style.animation_toast;private final Runnable timerrunnable = new Runnable () {@Overridepublic void run () {Removeview ();} };p rivate Toasthelper (Context context) {//notice:we should get application context//otherwise we'll get error//"Acti Vity has leaked window, was originally added "Context ctx = Context.getapplicationcontext (); if (CTX = = null) {CTX = con text;} This.mcontext = Ctx;mwindowmanager = (windowmanager) mcontext.getsystemservice (Context.window_service); init ();} private void Init () {mwindowparams = new windowmanager.layoutparams (); mwindowparams.flags = Windowmanager.layoutparams.flag_keep_screen_on| windowmanager.layoutparams.flag_not_touchable| Windowmanager.layoutparams.flag_not_focusable;mwindowparams.alpha = 1.0f;mwindowparams.width = Windowmanager.layoutparams.wrap_content;mwindowparams.height = WindowManager.LayoutParams.WRAP_CONTENT; mwindowparams.gravity = Gravity.center_horizontal | Gravity.bottom;mwindowparams.format = Pixelformat.translucent;mwindowparams.type = WindowManager.LayoutParams.TYPE _toast;mwindowparams.settitle ("Toasthelper"); mwindowparams.packagename = Mcontext.getpackagename (); Mwindowparams.windowanimations = animstyleid;//Todomwindowparams.y = mcontext.getresources (). GetDisplayMetrics (). WIDTHPIXELS/5;} @SuppressWarnings ("deprecation") @SuppressLint ("Newapi") Private View Getdefaulttoastview () {TextView view = new TextView (Mcontext); View.settext (mtoastcontent); View.setgravity (gravity.center_vertical | Gravity.start); view.setfocusable (false); view.setclickable (false); View.setfocusableintouchmode (false); View.settextcolor (android.grAphics. Color.White);D rawable drawable = Mcontext.getresources (). Getdrawable (Android. R.drawable.toast_frame), if (Build.VERSION.SDK_INT <) {view.setbackgrounddrawable (drawable);} else { View.setbackground (drawable);} return view;} public void Show () {Removeview (); if (Toastview = = null) {Toastview = Getdefaulttoastview ();} mwindowparams.gravity = android.support.v4.view.GravityCompat.getAbsoluteGravity (Gravity.center_horizontal | Gravity.bottom,android.support.v4.view.viewcompat.getlayoutdirection (Toastview)); RemoveView (); Mwindowmanager.addview (Toastview, Mwindowparams), if (Mhandler = = null) {Mhandler = new Handler ();} Mhandler.postdelayed (timerrunnable, duration);} public void Removeview () {if (Toastview! = null && toastview.getparent ()! = null) {Mwindowmanager.removeview (Toas TView); Mhandler.removecallbacks (timerrunnable);}} /** * @param context * @param content * @param duration * @return */public static Toasthelper Maketext (context context, St Ring Content,int duration) {ToasthelPer helper = new Toasthelper (context); helper.setduration (duration); helper.setcontent (content); return helper;} /** * @param context * @param Strid * @param duration * @return */public static Toasthelper Maketext (context context, int Strid, int duration) {Toasthelper helper = new Toasthelper (context); helper.setduration (duration); Helper.setcontent ( Context.getstring (Strid)); return helper;} Public toasthelper setcontent (String content) {this.mtoastcontent = Content;return this;} Public Toasthelper setduration (int. duration) {this.duration = Duration;return this;} Public toasthelper setanimation (int animstyleid) {This.animstyleid = Animstyleid;mwindowparams.windowanimations = This.animstyleid;return this;} /** * Custom View * * @param view */public toasthelper setview (view view) {This.toastview = View;return this;}}

In addition share a self-defined ANIM:

1. Show the animation of the toast:

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

><set xmlns:android= "http://schemas.android.com/apk/res/android" android:duration= " android: Fillafter= "true" > <alpha android:fromalpha= "0.0" android:toalpha= "1.0"/> < Translate android:fromydelta= "20%" android:toydelta= "0%"/> <scale android:fromxscale= " 0.5 " android:fromyscale=" 0.5 " android:pivotx=" 50% " android:pivoty=" 50% " android:toxscale=" 1.0 " android:toyscale=" 1.0 "/></set>


2. Exit the Toast Animation:

<set xmlns:android= "http://schemas.android.com/apk/res/android"    android:duration= "    android: Fillafter= "true" >    <alpha        android:fromalpha= "1.0"        android:toalpha= "0.0"/>    < Translate        android:fromydelta= "0%"        android:toydelta= "20%"/></set>


Adding an animation to a view in WindowManager requires defining a style, such as the following:

    <style name= "Poptoast" >        <item name= "@android: Windowenteranimation" > @anim/anim_toast_enter</ item>        <item name= "@android: Windowexitanimation" > @anim/anim_toast_exit</item>    </ Style>

Finally, it can be used as follows:

Toasthelper.maketext (This, "Hello World.") Harare speed is Right ", toasthelper.length_short). Setanimation (R.style.poptoast). Show ();


Iii. References:

Supertoast:https://github.com/johnpersano/supertoasts

Android self-defined toast

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.