首页 > 代码库 > 轻量级控件SnackBar应用&源码分析

轻量级控件SnackBar应用&源码分析

前言

         SnackBar是Android Support Design Library库支持的一个控件,它在使用的时候经常和CoordinatorLayout一起使用,它是介于Toast和Dialog之间的产物,属于轻量级控件很方便的提供提示和动作反馈,有时候我们需要这样的控件,和Toast一样显示便可以消失,又想这个消息提示上进行用户的反馈。然而写Dialog只能通过点击去取消它,所以SnackBar的出现更加让界面优雅。


Part 1、SnackBar的常规使用

Snackbar snackbar = Snackbar.make(v, R.string.tip, Snackbar.LENGTH_INDEFINITE);
                snackbar.setAction(R.string.know, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "click know", Toast.LENGTH_SHORT).show();
                    }
                });
                snackbar.setCallback(new Snackbar.Callback() {
                    @Override
                    public void onDismissed(Snackbar snackbar, int event) {
                        super.onDismissed(snackbar, event);
                        Toast.makeText(MainActivity.this, "onDismissed", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onShown(Snackbar snackbar) {
                        super.onShown(snackbar);
                        Toast.makeText(MainActivity.this, "onShown", Toast.LENGTH_SHORT).show();
                    }
                });
                snackbar.setActionTextColor(Color.GREEN);
                snackbar.show();
            }

效果~

技术分享

tips:

1、Snackbar.LENGTH_INDEFINITE : 无穷时间

2、SnackBar不能添加多个Action,当添加多个时,后一个会覆盖前一个

3、如果要监听SnackBar的显示和消失则设置setCallback

Part 2、SnackBar源码分析

SnackBar类make方法

    @NonNull
    public static Snackbar make(@NonNull View view, @NonNull CharSequence text,
            @Duration int duration) {
        Snackbar snackbar = new Snackbar(findSuitableParent(view));
        snackbar.setText(text);
        snackbar.setDuration(duration);
        return snackbar;
    }
构造方法

    private Snackbar(ViewGroup parent) {
        mTargetParent = parent;
        mContext = parent.getContext();

        ThemeUtils.checkAppCompatTheme(mContext);

        LayoutInflater inflater = LayoutInflater.from(mContext);
        mView = (SnackbarLayout) inflater.inflate(
                R.layout.design_layout_snackbar, mTargetParent, false);

        mAccessibilityManager = (AccessibilityManager)
                mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
    }
tips:

1、这里传入的view是一个锚点,然而在构造方法里面将findSuitableParent()返回的父类传入构造方法中

2、这里看一下R.layout.design_layout_snackbar.xml

<view xmlns:android="http://schemas.android.com/apk/res/android"
      class="android.support.design.widget.Snackbar$SnackbarLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom"
      style="@style/Widget.Design.Snackbar" />
这里使用了自定义View,路径为class=“android.support.design.widget.Snackbar&SnackbarLayout”;此为内部类,这里先不分析此类。

通过使用inflate方法将此View进行填充,由于最后一个参数为false,所以在SnackBar类肯定会有addView方法将此View添加到parent中

findSuitableParent()方法

    private static ViewGroup findSuitableParent(View view) {
        ViewGroup fallback = null;
        do {
            if (view instanceof CoordinatorLayout) {
                // We‘ve found a CoordinatorLayout, use it
                return (ViewGroup) view;
            } else if (view instanceof FrameLayout) {
                if (view.getId() == android.R.id.content) {
                    // If we‘ve hit the decor content view, then we didn‘t find a CoL in the
                    // hierarchy, so use it.
                    return (ViewGroup) view;
                } else {
                    // It‘s not the content view but we‘ll use it as our fallback
                    fallback = (ViewGroup) view;
                }
            }

            if (view != null) {
                // Else, we will loop and crawl up the view hierarchy and try to find a parent
                final ViewParent parent = view.getParent();
                view = parent instanceof View ? (View) parent : null;
            }
        } while (view != null);

        // If we reach here then we didn‘t find a CoL or a suitable content view so we‘ll fallback
        return fallback;
    }
tip:

这里为了找到描点的父容器,然而在此方法中使用了while循环将不断的查找父级控件等于CoordinatorLayout或者FrameLayout(也就是DecorView),并将得到的parent返回。

根据代码,将会执行setAction方法

    @NonNull
    public Snackbar setAction(CharSequence text, final View.OnClickListener listener) {
        final TextView tv = mView.getActionView();

        if (TextUtils.isEmpty(text) || listener == null) {
            tv.setVisibility(View.GONE);
            tv.setOnClickListener(null);
        } else {
            tv.setVisibility(View.VISIBLE);
            tv.setText(text);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    listener.onClick(view);
                    // Now dismiss the Snackbar
                    dispatchDismiss(Callback.DISMISS_EVENT_ACTION);
                }
            });
        }
        return this;
    }
这里只不过是将上面所说的那个自定义View设置内容

继续向下执行,为SnackBar的show方法

    /**
     * Show the {@link Snackbar}.
     */
    public void show() {
        SnackbarManager.getInstance().show(mDuration, mManagerCallback);
    }
这里又涉及到了一个新类SnackBarManager,从字面意思可只是一个管理SnackBar的类
    public void show(int duration, Callback callback) {
        synchronized (mLock) {
            if (isCurrentSnackbarLocked(callback)) {//(1)
                // Means that the callback is already in the queue. We‘ll just update the duration
                mCurrentSnackbar.duration = duration;

                // If this is the Snackbar currently being shown, call re-schedule it‘s
                // timeout
                mHandler.removeCallbacksAndMessages(mCurrentSnackbar);
                scheduleTimeoutLocked(mCurrentSnackbar);
                return;
            } else if (isNextSnackbarLocked(callback)) {//(2)
                // We‘ll just update the duration
                mNextSnackbar.duration = duration;
            } else {//(3)
                // Else, we need to create a new record and queue it
                mNextSnackbar = new SnackbarRecord(duration, callback);
            }

            if (mCurrentSnackbar != null && cancelSnackbarLocked(mCurrentSnackbar,
                    Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE)) {//(4)
                // If we currently have a Snackbar, try and cancel it and wait in line
                return;
            } else {//(5)
                // Clear out the current snackbar
                mCurrentSnackbar = null;
                // Otherwise, just show it now
                showNextSnackbarLocked();
            }
        }
    }

这里为了分析方便在每个判断都加上了标号

tips:

1、(1)中判断如果是当前SnackBar锁定则先将Handler移除队列中CallBack,然后在添加,这样就避免了等待,请注意这里用到的类是SnackbarRecord而不是SnackBar

2、(2)如果是下一个SnackBar则将Duration更新

ok,show()方法中传入了CallBack对象

    interface Callback {
        void show();
        void dismiss(int event);
    }
这里也就是这个接口,相应实现接口在哪里呢?这里我们回退到SnackBar的show()方法中传入了mManagerCallback,然而经过查找在SnackBar类中就有相应的实现

   final SnackbarManager.Callback mManagerCallback = new SnackbarManager.Callback() {
        @Override
        public void show() {
            sHandler.sendMessage(sHandler.obtainMessage(MSG_SHOW, Snackbar.this));
        }

        @Override
        public void dismiss(int event) {
            sHandler.sendMessage(sHandler.obtainMessage(MSG_DISMISS, event, 0, Snackbar.this));
        }
    };
到这里我们应该清楚:SnackBar和SnackBarManager之间通过CallBack来实现通信,而SnackBarManager维护的是Callback类。

由于上面添加的是是SnackBarRecord而不是SnackBar,来研究一下

    private static class SnackbarRecord {
        final WeakReference<Callback> callback;
        int duration;

        SnackbarRecord(int duration, Callback callback) {
            this.callback = new WeakReference<>(callback);
            this.duration = duration;
        }

        boolean isSnackbar(Callback callback) {
            return callback != null && this.callback.get() == callback;
        }
    }
tips:

只是存放了Callback和duration,这里值得学习是使用了弱引用类型来存储Callback,减少了ANR异常

这里对于SnackBar的流程大致完毕,对于回调类中show和dismiss方法,我们来看一下内部是如何进行处理的呢?

    static {
        sHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_SHOW:
                        ((Snackbar) message.obj).showView();
                        return true;
                    case MSG_DISMISS:
                        ((Snackbar) message.obj).hideView(message.arg1);
                        return true;
                }
                return false;
            }
        });
    }
showView()方法

    final void showView() {
        if (mView.getParent() == null) {
            final ViewGroup.LayoutParams lp = mView.getLayoutParams();

            ......
            }

            mTargetParent.addView(mView);
          .......//(2)
 }
ok,通过SnackBarManager调用Callback接口的show方法将View添加到了Parent中
在来看省略号(2)中的代码
        mView.setOnAttachStateChangeListener(new SnackbarLayout.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {}

            @Override
            public void onViewDetachedFromWindow(View v) {
                if (isShownOrQueued()) {
                    // If we haven‘t already been dismissed then this event is coming from a
                    // non-user initiated action. Hence we need to make sure that we callback
                    // and keep our state up to date. We need to post the call since removeView()
                    // will call through to onDetachedFromWindow and thus overflow.
                    sHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onViewHidden(Callback.DISMISS_EVENT_MANUAL);
                        }
                    });
                }
            }
        });

        if (ViewCompat.isLaidOut(mView)) {
            if (shouldAnimate()) {
                // If animations are enabled, animate it in
                animateViewIn();
            } else {
                // Else if anims are disabled just call back now
                onViewShown();
            }
        } else {
            // Otherwise, add one of our layout change listeners and show it in when laid out
            mView.setOnLayoutChangeListener(new SnackbarLayout.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View view, int left, int top, int right, int bottom) {
                    mView.setOnLayoutChangeListener(null);

                    if (shouldAnimate()) {
                        // If animations are enabled, animate it in
                        animateViewIn();
                    } else {
                        // Else if anims are disabled just call back now
                        onViewShown();
                    }
                }
            });
        }
tips:

view.setOnAttachStateChangeListener() : 监听View视图关联状态发生改变

来看一下animateViewIn()

    void animateViewIn() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            ViewCompat.setTranslationY(mView, mView.getHeight());
            ViewCompat.animate(mView)
                    .translationY(0f)
                    .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
                    .setDuration(ANIMATION_DURATION)
                    .setListener(new ViewPropertyAnimatorListenerAdapter() {
                        @Override
                        public void onAnimationStart(View view) {
                            mView.animateChildrenIn(ANIMATION_DURATION - ANIMATION_FADE_DURATION,
                                    ANIMATION_FADE_DURATION);
                        }

                        @Override
                        public void onAnimationEnd(View view) {
                            onViewShown();
                        }
                    }).start();
        } else {
            Animation anim = AnimationUtils.loadAnimation(mView.getContext(),
                    R.anim.design_snackbar_in);
            anim.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR);
            anim.setDuration(ANIMATION_DURATION);
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                    onViewShown();
                }

                @Override
                public void onAnimationStart(Animation animation) {}

                @Override
                public void onAnimationRepeat(Animation animation) {}
            });
            mView.startAnimation(anim);
        }
    }
这里分为大于3.0和小于3.0,分别使用相应的动画来实现SnackBar显示的动画

最后我们来看一下最上面说到的SnackBar所使用的自定义View

    /**
     * @hide
     */
    @RestrictTo(GROUP_ID)
    public static class SnackbarLayout extends LinearLayout {
继承了LinearLayout,默认情况为线性布局,这里只是添加了TextView和Button控件

            // Now inflate our content. We need to do this manually rather than using an <include>
            // in the layout since older versions of the Android do not inflate includes with
            // the correct Context.
            LayoutInflater.from(context).inflate(R.layout.design_layout_snackbar_include, this);
这里没有用include是为了兼容低版本,root是this意味将该布局添加到这个View中

design_layout_snackbar_include.xml:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
            android:id="@+id/snackbar_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingTop="@dimen/design_snackbar_padding_vertical"
            android:paddingBottom="@dimen/design_snackbar_padding_vertical"
            android:paddingLeft="@dimen/design_snackbar_padding_horizontal"
            android:paddingRight="@dimen/design_snackbar_padding_horizontal"
            android:textAppearance="@style/TextAppearance.Design.Snackbar.Message"
            android:maxLines="@integer/design_snackbar_text_max_lines"
            android:layout_gravity="center_vertical|left|start"
            android:ellipsize="end"
            android:textAlignment="viewStart"/>

    <Button
            android:id="@+id/snackbar_action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/design_snackbar_extra_spacing_horizontal"
            android:layout_marginStart="@dimen/design_snackbar_extra_spacing_horizontal"
            android:layout_gravity="center_vertical|right|end"
            android:paddingTop="@dimen/design_snackbar_padding_vertical"
            android:paddingBottom="@dimen/design_snackbar_padding_vertical"
            android:paddingLeft="@dimen/design_snackbar_padding_horizontal"
            android:paddingRight="@dimen/design_snackbar_padding_horizontal"
            android:visibility="gone"
            android:textColor="?attr/colorAccent"
            style="?attr/borderlessButtonStyle"/>

</merge>
至此,SnackBar的源码分析完毕






轻量级控件SnackBar应用&源码分析