Android Material Design 之 Snackbar

来源:互联网 发布:php 推送代码 编辑:程序博客网 时间:2024/05/22 17:50

概述

Snackbar 是一个类似于 Toast 的用来显示消息的条状控件。和 Toast 的不同之处在于,Toast 是在屏幕下方偏上一点的位置弹出来;而 Snackbar 是从屏幕下方弹出来,并显示在屏幕底部。

代码

代码和 Toast 类似

RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root_layout);Snackbar.make(rootLayout, "This is a snack bar!", Snackbar.LENGTH_SHORT).show();

可以看到 make 方法和 show 方法都是采用的 Toast 的设计风格。

make 方法的第二个和第三个参数和 Toast 一样,第一个参数是指定 Snackbar 的父控件,表示想在哪个 Layout 的底部显示一个 Snackbar。
但是有时候虽然指定了一个 Layout,但是 Snackbar 并不是显示在这个 Layout 的底部。这是为什么?
看一下 make 方法里面的 parent 取得方法

final ViewGroup parent = findSuitableParent(view);

再看一下 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;    }

意思就是
1. 如果传进去的 View 是 CoordinatorLayout,那么 View 就是 CoordinatorLayout。
2. 否则,一直向上取 parent 知道 parent 是 android.R.id.content,返回 android.R.id.content。
3. 否则,返回传进去的 View。

Snackbar 还可以在右侧设置按钮来添加事件,根据 Material Design 的设计原则,最多只可以添加 1 个按钮。

RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root_layout);Snackbar.make(rootLayout, "This is a snack bar!", Snackbar.LENGTH_SHORT)    .setAction("UNDO", new View.OnClickListener() {      @Override       public void onClick(View v) {       }     })     .show();

原创粉丝点击