前言:近来学习了Android Material Design 兼容库,为了把这个弄懂,才有了这篇博客,这里先推荐两篇博客:1.Android Material Design 兼容库的使用详解
2.Android应用Design Support Library完全使用实例
第一篇博客是这个兼容库的详细解析,我参考了里面的许多内容,第二篇是兼容库的大致介绍,如果你能把这两篇全部弄懂,我这篇也没有必要看了。说了这么多,开始正文吧,大家有什么问题或建议,欢迎留言交流。本文同时发布在简书:http://www.jianshu.com/p/8ec9cfc7a7b0
文章所用的示例地址:[mecury/MeterialDesignSupportLibrary]
1.概述
在2015年,google官方升级了Design Support Library,为开发者增加了不少可用的开发控件。
2综述
支持Android 2.1以上设备。
Gradle build script dependency:
compile 'com.android.support:design:22.2.0' //可修改版本号为自己匹配
Design Support Library包含8个控件,具体如下:
- android.support.design.widget.TextInputLayout
强大带提示的MD风格的EditText - android.support.design.widget.FloatingActionButton
MD风格的圆形按钮,来自于ImageView
+android.support.design.widget.Snackbar
类似Toast,添加了简单的单个Action - android.support.design.widget.TabLayout
选项卡 - android.support.design.widget.NavigationView
DrawerLayout的SlideMenu - android.support.design.widget.CoordinatorLayout
超级FrameLayout - android.support.design.widget.AppBarLayout
MD风格的滑动Layout - android.support.design.widget.CollapsingToolbarLayout
可折叠MD风格ToolbarLayout
注意事项:
这里需要添加额外的命名空间appNs(xmlns:app="http://schemas.android.com/apk/res-auto" )
在介绍各个控件之前,大家先看一下预览图,这里我自己写了一个示例,看起来不太好,但是用来介绍是够了,下面看图。
2.1 FLoatingActionButton
演示gif
一 个负责显示界面基本操作的圆形按钮。Design library中的FloatingActionButton 实现了一个默认颜色为主题中colorAccent的悬浮操作按钮。FloatingActionButton继承自ImageView,你可以通过 android:src或者 ImageView的任意方法,比如setImageDrawable()来设置FloatingActionButton里面的图标。下面介绍几种常用 的设置属性:
- app:fabSize 设置按钮的大小,有mini和normal可选,默认为normal
- app:elevation 设置按钮的高度,影响阴影范围的显示
- app:rippleColor 设置涟漪效果的颜色(当点击按钮时的水波纹)
code:<android.support.design.widget.FloatingActionButton android:id="@+id/floatingButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher" app:elevation="5dp" app:fabSize="normal" />
无特别注意项,和普通控件类似。
2.2 TextInputLayout
演示gif:
在MD中,使用TextInputLayout将EditText进行了封装。其最大的改变就是为EditText添加了两个提示效果。一个显示在上面,提示用户输入的是什么,另一个可以设为Error提示,当输入错误的时候显示出来。
code:
<android.support.design.widget.TextInputLayout android:id="@+id/textInput" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.design.widget.TextInputLayout>
在代码中使用的是时候,需要监听EditText的变化。
editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.e("TAG",s.length()+""); if (s.length() > 4){ inputLayout.setError("字符不能超过5个"); inputLayout.setErrorEnabled(true); }else{ inputLayout.setErrorEnabled(false); } } @Override public void afterTextChanged(Editable s) { } });
注意项
TextInputLayout中至少嵌套一个EditText。
2.3 SnackBar
演示gif:
SnackBar 提供一个轻量