Android Material Design 之 Snackbar

概述

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值