Android Toast Advanced--Custom toast

Source: Internet
Author: User

Directory structure

    • Directory structure
    • Objective
    • Advanced Target
    • Control toast Display Time
    • Modify a Toast animation effect

Objective

CSDN unexpectedly support markdown grammar, to me this lazy to build blog person is really good news, and then review markdown Grammar, I am ready to write an Android toast advanced with markdown grammar rewrite again.

Advanced Target

On a blog we learned the toast of the source, understand the toast from the display to disappear the whole process, learning link: Android toast source analysis. As the saying goes, it's good. We learn toast source code is not used to dazzle, but to understand the toast principle, so as to really solve our problems. I'll mention some of the two real-world toast-related issues that you might encounter in your business, and see how you can solve these problems after learning the toast source. Two questions are:
1. How to customize the display time of a toast.
2. How to modify the appearance of toast animation.
Next, we explain how to solve the real problems in the two businesses after reading the toast source.

Control toast Display Time

Through the study of toast source, we know that the display and disappearance of toast is implemented by Notificationmanagerservice calling the show and hide methods of the TN class, The length of time the toast is displayed is related to the delay time that handler sends the message. The specific source code is as follows:

privatevoidscheduleTimeoutLocked(ToastRecord r){    mHandler.removeCallbacksAndMessages(r);    Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);    long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;    mHandler.sendMessageDelayed(m, delay);}

Before the toast source also said, why Toast desktop display time can only be 2s and 3.5s, the key is that long delay variable delay time can only be 2s and 3.5s. So if you are a developer of the Android operating system, you can directly modify the Android framework layer's Notificationmanagerservice class code, which will long_delay and Short_ Delay changes to the time interval you want. However, the drawbacks of this approach are obvious. First of all, you may only be a small application layer development engineer, can only change the application layer code. Second, even if modified notificationmanagerservice, can only change the Long_delay and Short_delay two variables, can not be arbitrarily modified display time.
So many drawbacks, what should we do with the application layer development engineer? The answer is also very simple, modeled after the toast source, we build a wheel, customize a toast, so that we can certainly control the toast display time. Through the source we know that toast is based on WindowManager to display, then we can completely masturbate a custom toast out, the source code is as follows:

ImportAndroid.content.Context;ImportAndroid.graphics.PixelFormat;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.view.Gravity;ImportAndroid.view.View;ImportAndroid.view.WindowManager;ImportAndroid.widget.Toast; Public  class toastcustom {    Private Static Final intMessage_timeout =2;PrivateWindowManager WDM;Private DoubleTimePrivateView MView;PrivateWindowmanager.layoutparams params;PrivateWorkerhandler Mhandler;Private Toastcustom(Context context, String text,DoubleTime) {WDM = (WindowManager) context.getsystemservice (Context.window_service); Mhandler =NewWorkerhandler ();        Toast Toast = Toast.maketext (context, text, toast.length_long);        MView = Toast.getview (); params =NewWindowmanager.layoutparams ();        Params.height = WindowManager.LayoutParams.WRAP_CONTENT;        Params.width = WindowManager.LayoutParams.WRAP_CONTENT;        Params.format = pixelformat.translucent; Params.windowanimations = Toast.getview (). Getanimation ().        INFINITE;        Params.type = WindowManager.LayoutParams.TYPE_TOAST; Params.settitle ("Toast"); params.gravity = Gravity.center_horizontal |        gravity.center_vertical; Params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; This. Time = time; } Public StaticToastcustomMaketext(Context context, String text,DoubleTime) {Toastcustom Toastcustom =NewToastcustom (context, text, time);returnToastcustom; } Public void Show() {Wdm.addview (MView, params); Mhandler.sendemptymessagedelayed (Message_timeout, (Long) (Time * +)); } Public void Cancel() {Wdm.removeview (MView); }Private  class workerhandler extends Handler {        @Override         Public void Handlemessage(Message msg) {Switch(msg.what) { CaseMessage_timeout:cancel (); Break; }        }    }}

The principle is simple, use WindowManager to display toasts, and then use the handler mechanism to send deferred message control WindowManager and then delete the toast. One thing to note: The handler of the custom toast here is also the looper of the main thread, and the child threads calling the custom toast need to add looper.prepare () and Looper.loop () code.

Modify a Toast animation effect

Android native Toast class does not give us an animated interface, each Android native Toast animation effect is defined in the TN class Com.android.internal.r.style.animation_ Toast, so if you want to modify Android? Toast animation effect, or you need to make a toast, modify the contents of the params.windowanimations variable. Next, let's customize an animation effect first. Define a new style,xml content in the Style.xml file as follows:

<style name="custom_toast_anim_view">    <item name="@android:windowEnterAnimation">@anim/enter_anim</item>    <item name="@android:windowExitAnimation">@anim/exit_anim</item></style>

Then add two animation effects files under the Anim folder, Enter_anim.xml and Exit_anim.xml, respectively.

  • Enter_anim.xml

    <?xml version= "1.0" encoding= "Utf-8"?><set xmlns:android="Http://schemas.android.com/apk/res/android" ><translateandroid:duration="1"android:fromxdelta="0"  Android:fromydelta="0"android:toxdelta="0"android:toydelta= "/>"                     <translate  android: Fromxdelta  = "0"  android:fromydelta  =< Span class= "Hljs-value" > "0"  android:toxdelta  =     "0"  android:toydelta  = " -100"  android:duration  =  = "true"  android: Interpolator  = "@android: Anim/decelerate_interpolator" /> <alpha  android:duration  = android:fromalpha  = "0"  android:toalpha  = "1"  /> <translateandroid:duration="android:fillafter" ="true" Android:fromxdelta="0"android:fromydelta="0"android:startoffset ="android:toxdelta" = "0"android:toydelta=" />"                             </Set>
  • Exit_anim.xml

    <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" ><alpha    android:duration="800"    android:fromAlpha="1"    android:toAlpha="0" /></set>

    Then, modify the params.windowanimations variable in your custom toast code:

    params.windowAnimations = com.example.photocrop.R.style.custom_toast_anim_view;

Android Toast Advanced--Custom 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.