Android Design Support Library系列

作者: 滴滴滴9527 | 来源:发表于2017-05-19 22:24 被阅读0次
一、Snackbar介绍

Snackbar作为Android Design Support Library中的一员,使用时并不需要在布局文件中声明,直接在java代码中使用就可以了。
使用前添加依赖:

compile 'com.android.support:design:25.3.1'

Snackbar效果:
1)和Toast 一样,Snackbar能弹出一条消息
2)一小段时间之后、或者用户与屏幕触发交互,Snackbar 会自动消失
3)一个时刻只能有唯一一个 Snackbar 显示
4)和Toast 不同的是,Snackbar 可以设置一个Action与用户发生交互

二、Snackbar简单使用

惯例,给出官方文档
Toast大家都使用过,像下面这样:

Toast.makeText(mContext, "Toast", Toast.LENGTH_SHORT).show();

Snackbar使用和Toast极其相似:

Snackbar.make(view, "Snackbar", Snackbar.LENGTH_SHORT).show();

ok,来看一下Snackbar的简单使用:
布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt"
        android:text="苦海,泛起爱恨"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

java代码

public class MainActivity extends AppCompatActivity {

    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt = (Button) findViewById(R.id.bt);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(bt,"Snackbar",Snackbar.LENGTH_SHORT).show();
            }
        });
    }
}

效果图



这里我通过点击Button,弹出Snackbar(不要管Button的内容,那只是我正在听的歌词......)

同Toast使用差不多,Snackbar使用时也需要3个参数,第二个参数、第三个参数和Toast一样,分别是:显示的文本、时间,不同的是Toast第一个参数是Context,而Snackbar第一个参数需要的是一个View对象。

三、Snackbar与用户交互

与Toast不同的是,Snackbar可以与用户发生交互,只要给它设置一个Action就可以了。

Snackbar.make(bt,"Snackbar",Snackbar.LENGTH_SHORT).
    setAction("交互", new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
          }
  }).show();

当然,如果你不喜欢链式的写法,可以拆开:

Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
mSnackbar.setAction("交互", new View.OnClickListener() {
         @Override
          public void onClick(View v) {
             Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
          }
});
mSnackbar.show();

效果图:


四、更改Snackbar样式

1、修改Action中字体颜色
Action中字体颜色默认使用theme中的colorAccent颜色:

 <item name="colorAccent">@color/colorAccent</item>

Snackbar提供了下面这个方法来修改Action中字体颜色

setActionTextColor()
    Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
    mSnackbar.setAction("交互", new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
        }
    });
    mSnackbar.setActionTextColor(Color.WHITE);
    mSnackbar.show();

效果图:


2、修改Snackbar背景及提示消息字体颜色
Snackbar并没有直接提供方法来设置背景、消息字体颜色的方法,不过Snackbar提供了一个方法来返回一个View对象:
Snackbar.getView()

那么这个View对象代表着什么呢?观看源码

    public static Snackbar make(@NonNull View view, @NonNull CharSequence text, @Duration int duration) {
        final ViewGroup parent = findSuitableParent(view);
        if (parent == null) {
            throw new IllegalArgumentException("No suitable parent found from the given view. "
                    + "Please provide a valid view.");
        }

        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        final SnackbarContentLayout content =
                (SnackbarContentLayout) inflater.inflate( R.layout.design_layout_snackbar_include, parent, false);  //☆   
        final Snackbar snackbar = new Snackbar(parent, content, content);
        snackbar.setText(text);
        snackbar.setDuration(duration);
        return snackbar;
    }

看到源码之后发现:原来Snackbar 显示的内容是一个布局填充而来的,接着我又找到那个布局:

<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->

<view
    xmlns:android="http://schemas.android.com/apk/res/android"
    class="android.support.design.internal.SnackbarContentLayout"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom">

    <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:minWidth="48dp"
        android:visibility="gone"
        android:textColor="?attr/colorAccent"
        style="?attr/borderlessButtonStyle"/>

</view>

一看,原来消息是一个TextView,Action按钮是一个Button,看到这,我顿时知道该怎么做了O(∩_∩)O
这不就是一个布局文件吗,想要设置什么直接findViewById找到那个组件直接设置不就可以了...

Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
mSnackbar.setAction("交互", new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Toast.makeText(MainActivity.this, "白云外", Toast.LENGTH_SHORT).show();
     }
});
 mSnackbar.setActionTextColor(Color.WHITE);

View view = mSnackbar.getView();
view.setBackgroundColor(Color.parseColor("#ff0099cc"));
TextView tv = (TextView) view.findViewById(R.id.snackbar_text);
tv.setTextColor(Color.GREEN);
mSnackbar.show();

ok,效果很满意!更多的样式可以自己去设置,反正不就是一个TextView和一个Button吗O(∩_∩)O

五、Snackbar设置回调
mSnackbar.setCallback(new Snackbar.Callback(){
       @Override
       public void onShown(Snackbar sb) {
           super.onShown(sb);
           Toast.makeText(MainActivity.this,"onShown",Toast.LENGTH_SHORT).show();
       }
       @Override
       public void onDismissed(Snackbar transientBottomBar, int event) {
          super.onDismissed(transientBottomBar, event);
          Toast.makeText(MainActivity.this,"onDismissed",Toast.LENGTH_SHORT).show();
       }
});

Snackbar可以设置一个回调,里面有两个方法:Snackbar显示的时候调用、Snackbar消失的时候调用。


六、Snackbar在CoordinateorLayout容器中

Snackbar需要一个容器,而这个容器官方推荐的CoordinatorLayout,观看Snackbar的源码,发现:
Snackbar 会遍历视图树找到一个合适的容器作为载体,而这个载体首选的就是CoordinatorLayout。

    public static Snackbar make(@NonNull View view, @NonNull CharSequence text,
            @Duration int duration) {

        final ViewGroup parent = findSuitableParent(view);//☆☆☆☆☆

        if (parent == null) {
            throw new IllegalArgumentException("No suitable parent found from the given view. "
                    + "Please provide a valid view.");
        }

        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        final SnackbarContentLayout content =
                (SnackbarContentLayout) inflater.inflate(
                        R.layout.design_layout_snackbar_include, parent, false);
        final Snackbar snackbar = new Snackbar(parent, content, content);
        snackbar.setText(text);
        snackbar.setDuration(duration);
        return snackbar;
    }

    private static ViewGroup findSuitableParent(View view) {
        ViewGroup fallback = null;
        //遍历视图树
        do {
            if (view instanceof CoordinatorLayout) {
                // We've found a CoordinatorLayout, use it      首选是CoordinatorLayout作为载体
                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;
    }

那么使用CoordinatorLayout作为载体有什么好处呢?
我在布局文件中又加入了一个FloatingActionButton浮在右下角:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="苦海,泛起爱恨" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:src="@mipmap/add" />

</RelativeLayout>

可以看见,Snackbar把FloatingActionButton挡住了,这对用户来说体验很不好.

那么使用CoordinatorLayout试试看,CoordinatorLayout是什么呢?
CoordinatorLayout是Android Design Support Library中另外一个组件,后面会单独写一篇文章来介绍它,其本质是一个超级FrameLayout,主要是作为根标签使用,协调各个子布局。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="苦海,泛起爱恨" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|bottom"
        android:src="@mipmap/add" />

</android.support.design.widget.CoordinatorLayout>

可以看见,使用CoordinatorLayout之后,Snackbar弹出的时候,FloatingActionButton会自动上升,而且Snackbar可以通过向右滑动取消。

相关文章

网友评论

    本文标题:Android Design Support Library系列

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