美文网首页
Toast的用法和源码解析

Toast的用法和源码解析

作者: 壹公升 | 来源:发表于2016-09-06 16:40 被阅读0次

    Toast是我们在App开发过程常用的提示用户进行了一些操作又不影响用户正常操作的一个Android开发常用的控件
    1.最基本的Toast用法
    通过makeText(Context, String,Int)方法初始化一个Toast对象调用show方法进行显示,代码如下
    <code>Toast t =Toast.makeText(this,"BasicsToast",Toast.LENGTH_SHORT);
    t.show();</code>

    通常都可以简写成
    <code>
    Toast.makeText(this,"BasicsToast",Toast.LENGTH_SHORT).show();</code>
    2.设置Toast的显示位置
    通常一个Toast的信息是显示在接近屏幕的底部居中,但是有些时候我们需要自定义它显示位置的时候可是使用Toast的setGravity方法进行自定义,这个方法需要三个参数Gravity常量,X偏移量,Y偏移量,代码如下:
    <code>
    Toast t =Toast.makeText(this,"BasicsToast",Toast.LENGTH_SHORT);
    t.setGravity(Gravity.CENTER,0 ,0);
    t.show();</code>
    3.自定义Toast显示内容
    Toast的默认方法只可以显示文字,当我们需要显示图片或者图片和文字结合的自定义内容时可以使用Toast提供的setView方法进行设置我们自定义显示的内容了代码如下:
    首先定义需要显示的布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"    
    android:layout_width="match_parent"
    android:layout_height="match_parent"  >
    <TextView        
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"       
    android:text="标题"        
    android:layout_gravity="center_horizontal"/>
    <ImageView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"        
    android:background="@drawable/test"/>
    </LinearLayout>
    

    然后加载布局文件设置自定义Toast并显示

    Toast toast = new Toast(this);
    toast.setView(LayoutInflater.from(this).inflate(R.layout.custom_toast_layout, null, false));
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.show();
    

    4.自定义显示时间
    Toast的设置显示时间的方法<code>setDuration()</code>的参数只能是<code>Toast.LENGTH_SHORT</code>和<code>Toast.LENGTH_LONG</code>两个;那么我们怎么去自定义Toast显示时间呢,这就需要我们去了解Toast的源码和Toast的原理来实现了
    首先我们从Toast的<code>makeText(Context,CharSequence,int)</code>方法入手

    Toast result = new Toast(context);
    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;
    

    从代码我们可以看出来<code>makeText()</code>方法的作用主要就是构造一个Toast对象,加载Toast显示的布局,设置显示时间。
    我们继续看一下<code>show()</code>方法来看一下Toast怎么实现显示

    if (mNextView == null) {
    throw new RuntimeException("setView must have been called");
    }
    INotificationManager service = getService();
    String pkg = mContext.getOpPackageName();
    TN tn = mTN;
    tn.mNextView = mNextView;
    try {
    service.enqueueToast(pkg, tn, mDuration);
    } catch (RemoteException e) {  
      // Empty
    }
    

    从<code>show()</code>方法的代码我们可以看出在调用<code>show()</code>方法的时候会先构造一个TN然后键Toast显示相关信息发送到一个消息队列等待显示
    那么Toast显示的控制在哪里?
    我们可以看一下TN这个类

    final Runnable mShow = new Runnable() {
    @Override    
    public void run() {        
    handleShow();    
      }
    };
    final Runnable mHide = new Runnable() {    
    @Override    
    public void run() {        
    handleHide();    
    //Don't do this in handleHide() because it is also invoked by handleShow()        
    mNextView = null;
        }
    };
    

    我们可以看到在TN里面定义了两个Runnable <code>mShow</code>和<code>mHide</code>来控制Toast的显示和消失
    我们接下来看下<code>handleShow</code>方法的实现

    if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView        + " mNextView=" + mNextView);
    if (mView != mNextView) {
        // remove the old view if necessary    handleHide();
        mView = mNextView;
        Context context = mView.getContext().getApplicationContext();
        String packageName = mView.getContext().getOpPackageName();
        if (context == null) {
            context = mView.getContext();
        }
    mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
    // We can resolve the Gravity here by using the Locale for getting
    // the layout direction
    final Configuration config = mView.getContext().getResources().getConfiguration();
    final int gravity = Gravity.getAbsoluteGravity(mGravity,config.getLayoutDirection());
    mParams.gravity = gravity;
    if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
         mParams.horizontalWeight = 1.0f;
    }
    if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
         mParams.verticalWeight = 1.0f;
     }
    mParams.x = mX;
    mParams.y = mY;
    mParams.verticalMargin = mVerticalMargin;
    mParams.horizontalMargin = mHorizontalMargin;    
    mParams.packageName = packageName;
    if (mView.getParent() != null) {
         if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
         mWM.removeView(mView);
    }
    if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);    
    mWM.addView(mView, mParams);
    trySendAccessibilityEvent();
    }
    

    在handleShow方法中对要显示的view的参数进行设置然后同过WindowManager的addView方法进行显示!
    到这里我们总算弄清楚Toast显示的原理:
    通过<code>makeText()</code>方法初始化Toast对象调用<code>show()</code>方法初始化一个TN并将需要显示的内容传入一个消息队列等待显示,在TN中通过<code>mShow</code>和<code>mHide</code>控制Toast的显示。
    那么我们怎么自定义Toast显示时间?
    1.调用TN的mHide和mShow自己随心所欲的控制(因为TN类是私有的仅限包访问,所以我们需要使用java的反射来实现,但是这个方法在高版本会有bug)
    2.自定义一个Toast,不让消息进队列 我们自己处理
    3.使用Timer和handle.post相结合定时show一个Tosat
    下面我们就着重说一下第二种实现方法自己定义一个Toast来实现自定义显示时间的Toast,代码如下

    package song.com.toasttest;
    
    import android.content.Context;
    import android.graphics.PixelFormat;import android.os.Handler;
    import android.view.Gravity;import android.view.LayoutInflater;
    import android.view.View;import android.view.WindowManager;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    public class MyToast {
        private final Handler mHandler = new Handler();
        private int mDuration = 2000;
        private int mGravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        private int mX = 30;
        private int mY = 30;
        private float mHorizontalMargin;
        private float mVerticalMargin;
        private View mView;
        private View mNextView;
        private WindowManager mWindow;
        private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
        public MyToast(Context context) {
            final WindowManager.LayoutParams params = mParams;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
            params.format = PixelFormat.TRANSLUCENT;
            params.windowAnimations = android.R.style.Animation_Toast;
            params.type = WindowManager.LayoutParams.TYPE_TOAST;
            params.setTitle("Toast");
            mWindow = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        }
        //初始化Toast所需要的参数
        public static MyToast makeText(Context context, CharSequence text, int duration) {
            MyToast myToast = new MyToast(context);
            LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.my_toast_layout, null, false);
            TextView textView = (TextView) layout.findViewById(R.id.message);
            textView.setText(text);
            myToast.mNextView = layout;
            myToast.mDuration = duration;
            return myToast;
        }
        public int getmDuration() {
            return mDuration;
        }
        public void setmDuration(int mDuration) {
            this.mDuration = mDuration;
        }
        public int getmGravity() {
            return mGravity;
        }
        public void setmGravity(int mGravity) {
            this.mGravity = mGravity;
        }
        public float getmHorizontalMargin() {
            return mHorizontalMargin;
        }
        public void setmHorizontalMargin(float mHorizontalMargin) {
            this.mHorizontalMargin = mHorizontalMargin;
        }
        public float getmVerticalMargin() {
            return mVerticalMargin;
        }
        public void setmVerticalMargin(float mVerticalMargin) {
            this.mVerticalMargin = mVerticalMargin;
        }
        public View getmView() {
            return mView;
        }
        public void setmView(View mView) {
            this.mView = mView;
        }
        public void show() {
            mHandler.post(mShow);
            if (mDuration > 0) {
                mHandler.postDelayed(mHide, mDuration);
            }
        }
        private final Runnable mShow = new Runnable() {
            @Override
            public void run() {
                handleShow();
            }
        };
        private final Runnable mHide = new Runnable() {
            @Override
            public void run() {
                handleHide();
            }
        };
        private void handleShow() {
            if (mView != mNextView) {
                handleHide();
                mView = mNextView;
                mParams.gravity = mGravity;
                if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
                    mParams.horizontalMargin = 1.0f;
                }
                if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
                    mParams.verticalMargin = 1.0f;
                }
                mParams.x = mX;
                mParams.y = mY;
                mParams.horizontalMargin = mHorizontalMargin;
                mParams.verticalMargin = mVerticalMargin;
                if (mView.getParent() != null) {
                    mWindow.removeView(mView);
                }
                mWindow.addView(mView, mParams);
            }
        }
        private void handleHide() {
            if (mView != null) {
                if (mView.getParent() != null) {
                    mWindow.removeView(mView);
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Toast的用法和源码解析

          本文链接:https://www.haomeiwen.com/subject/yzudettx.html