Android进阶系列--Design Support Library使用详解(Snackbar,TextInputLayout,TabLayout,NavigationView...)

原文链接:http://blog.csdn.net/sw5131899/article/details/53996800


 *本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布


Material Design 设计风格非常受欢迎,那么支持其效果的Design Support Library(Android 2.1  API  level 7及其以上)库又有哪些控件呢。主要包括SnackBar、Navigation View、FloatActionbutton、CoordinatorLayout、CollapsingToolBarLayout等。我在Git上看见一个非常炫的效果

谷歌官网介绍:http://android-developers.blogspot.com.es/2012/05/android-design-support-library.html


把该项目的Git附上,觉得有用的自行下载看源码:https://github.com/frogermcs/InstaMaterial,现在来一一介绍Design系列控件。这里还有极客学院整理的关于Material Design的文档:

http://wiki.jikexueyuan.com/project/material-design/components/snackbars-and-toasts.html

1.SnackBar

SnackBar是带有动画效果的快速提示栏,它显示在屏幕底部,是用来代替Toast的一个全新控件,它基本上继承了Toast的属性和方法,用户可以点击按钮执行对应的操作,Snackbar支持滑动消失,如果没设任何操作,那么到时间自动消失。

SnackBar的构造:

// 参数分别是父容器,提示信息,持续时间
public
static Snackbar make(@NonNull View view, @NonNull CharSequence text,@Duration int duration)

SnackBar的常用方法:

// 用于给SnackBar设定一个Action,点击之后会回调OnclickListener中的Onclick方法
public
Snackbar setAction(CharSequence text, final View.OnClickListener listener)
// 用于设定Action的字体颜色
public
Snackbar setActionTextColor(@ColorInt int color)
// 设定提示的字体
public
Snackbar setText(@NonNull CharSequence message)
// 展示SnackBar
public
void show()
// 清除SnackBar
public
void dismiss()
// 设置回调,比如OnDismissed或者OnShown
public
Snackbar setCallback(Callback callback)
Snackbar需要一个控件容器view用来容纳,官方推荐使用CoordinatorLayout来确保Snackbar和其他组件的交互,比如滑动取消Snackbar、Snackbar出现时FloatingActionButton上移。举一个简单运用的例子:

  1. <android.support.percent.PercentRelativeLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     android:id="@+id/activity_main"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     tools:context="com.example.administrator.singleinstance.MainActivity">  
  9.   
  10.     <Button  
  11.         android:layout_width="0dp"  
  12.         android:layout_height="0dp"  
  13.         android:id="@+id/btn"  
  14.         android:onClick="click"  
  15.         android:layout_centerInParent="true"  
  16.         app:layout_widthPercent="25%"  
  17.         app:layout_heightPercent="10%"  
  18.         android:text="取消"  
  19.         />  
  20.   
  21.     <android.support.design.widget.CoordinatorLayout  
  22.         android:id="@+id/coor"  
  23.         android:layout_width="0dp"  
  24.         android:layout_alignParentBottom="true"  
  25.         app:layout_widthPercent="100%"  
  26.         android:layout_height="wrap_content">  
  27.   
  28.     </android.support.design.widget.CoordinatorLayout>  
  29.   
  30. </android.support.percent.PercentRelativeLayout>  
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.singleinstance.MainActivity">

    <Button
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/btn"
        android:onClick="click"
        android:layout_centerInParent="true"
        app:layout_widthPercent="25%"
        app:layout_heightPercent="10%"
        android:text="取消"
        />

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coor"
        android:layout_width="0dp"
        android:layout_alignParentBottom="true"
        app:layout_widthPercent="100%"
        android:layout_height="wrap_content">

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

</android.support.percent.PercentRelativeLayout>
  1. public void click(View view) {  
  2.         Snackbar.make(coordinatorLayout, "确定取消吗?", Snackbar.LENGTH_LONG)  
  3.                 .setAction("确定"new View.OnClickListener() {  
  4.                     @Override  
  5.                     public void onClick(View view) {  
  6.                         Toast.makeText(MainActivity.this"已经取消", Toast.LENGTH_SHORT).show();  
  7.                     }  
  8.                 })  
  9.                 .setCallback(new myOnClick())  
  10.                 .show();  
  11.   
  12.     }  
  13.   
  14.     /** 
  15.      * 滑动消失回调 
  16.      */  
  17.     public static final int DISMISS_EVENT_SWIPE = 0;  
  18.     /** 
  19.      * 点击消失回调 
  20.      */  
  21.     public static final int DISMISS_EVENT_ACTION = 1;  
  22.     /** 
  23.      * 超时回调 
  24.      */  
  25.     public static final int DISMISS_EVENT_TIMEOUT = 2;  
  26.     /** 
  27.      *调用Dismiss消失回调 
  28.      */  
  29.     public static final int DISMISS_EVENT_MANUAL = 3;  
  30.     /** 
  31.      * 再次出现消失SnackBar回调 
  32.      */  
  33.     public static final int DISMISS_EVENT_CONSECUTIVE = 4;  
  34.   
  35.     class myOnClick extends Snackbar.Callback {  
  36.         @Override  
  37.         public void onDismissed(Snackbar snackbar, int event) {  
  38.             super.onDismissed(snackbar, event);  
  39.             switch (event) {  
  40.                 case DISMISS_EVENT_SWIPE:  
  41.                     Logger.i("DISMISS_EVENT_SWIPE");  
  42.                     break;  
  43.                 case DISMISS_EVENT_ACTION:  
  44.                     Logger.i("DISMISS_EVENT_ACTION");  
  45.                     break;  
  46.                 case DISMISS_EVENT_TIMEOUT:  
  47.                     Logger.i("DISMISS_EVENT_TIMEOUT");  
  48.                     break;  
  49.                 case DISMISS_EVENT_MANUAL:  
  50.                     Logger.i("DISMISS_EVENT_MANUAL");  
  51.                     break;  
  52.                 case DISMISS_EVENT_CONSECUTIVE:  
  53.                     Logger.i("DISMISS_EVENT_CONSECUTIVE");  
  54.                     break;  
  55.             }  
  56.         }  
  57.     }  
public void click(View view) {
        Snackbar.make(coordinatorLayout, "确定取消吗?", Snackbar.LENGTH_LONG)
                .setAction("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, "已经取消", Toast.LENGTH_SHORT).show();
                    }
                })
                .setCallback(new myOnClick())
                .show();

    }

    /**
     * 滑动消失回调
     */
    public static final int DISMISS_EVENT_SWIPE = 0;
    /**
     * 点击消失回调
     */
    public static final int DISMISS_EVENT_ACTION = 1;
    /**
     * 超时回调
     */
    public static final int DISMISS_EVENT_TIMEOUT = 2;
    /**
     *调用Dismiss消失回调
     */
    public static final int DISMISS_EVENT_MANUAL = 3;
    /**
     * 再次出现消失SnackBar回调
     */
    public static final int DISMISS_EVENT_CONSECUTIVE = 4;

    class myOnClick extends Snackbar.Callback {
        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            switch (event) {
                case DISMISS_EVENT_SWIPE:
                    Logger.i("DISMISS_EVENT_SWIPE");
                    break;
                case DISMISS_EVENT_ACTION:
                    Logger.i("DISMISS_EVENT_ACTION");
                    break;
                case DISMISS_EVENT_TIMEOUT:
                    Logger.i("DISMISS_EVENT_TIMEOUT");
                    break;
                case DISMISS_EVENT_MANUAL:
                    Logger.i("DISMISS_EVENT_MANUAL");
                    break;
                case DISMISS_EVENT_CONSECUTIVE:
                    Logger.i("DISMISS_EVENT_CONSECUTIVE");
                    break;
            }
        }
    }
这些运用都很简单,就不更多的嚼舌根了。有个花式使用SnackBar的连接,感兴趣的可以去看看:

http://www.jianshu.com/p/cd1e80e64311

2.TextInputLayout

TextInputLayout主要作用是作为EditText的容器,从而为EditText默认生成一个浮动的label,当用户点击了EditText之后,EditText中设置的Hint字符串会自动移到EditText的左上角。使用非常简单

这有个例子写的不错:http://www.jcodecraeer.com/a/basictutorial/2015/0821/3338.html

  • getEditText() 得到控件中包含的 EditText 控件
  • setError(CharSequence error) 设置错误信息并显示在 EditText 下方 应用场景:比如用户输错了密码或者用户名等
  • setHint(CharSequence hint) 设置提示信息

  • setErrorEnabled(boolean enabled) 设置 setError(CharSequence error) 这个函数是否可用 记住哦:这个函数一定要在 setError(CharSequence error) 这个函数之后执行哦!

  1. <android.support.percent.PercentRelativeLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     android:id="@+id/activity_main"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     tools:context="com.example.administrator.singleinstance.MainActivity">  
  9.   
  10.     <android.support.design.widget.TextInputLayout  
  11.         android:id="@+id/input"  
  12.         app:layout_widthPercent="80%"  
  13.         android:layout_height="wrap_content"  
  14.         android:layout_centerHorizontal="true"  
  15.         app:errorEnabled="true"  
  16.         app:errorTextAppearance="@style/TextAppearance.Design.Error">  
  17.         <EditText  
  18.             android:layout_width="match_parent"  
  19.             android:layout_height="match_parent"  
  20.             android:imeOptions="actionGo"  
  21.             android:inputType="text"  
  22.             android:hint="输入姓名"  
  23.             android:lines="1"  
  24.             />  
  25.   
  26.     </android.support.design.widget.TextInputLayout>  
  27.     <android.support.design.widget.TextInputLayout  
  28.         android:id="@+id/input2"  
  29.         android:layout_below="@+id/input"  
  30.         app:layout_widthPercent="80%"  
  31.         android:layout_height="wrap_content"  
  32.         android:layout_centerHorizontal="true"  
  33.         app:errorEnabled="true"  
  34.         app:errorTextAppearance="@style/TextAppearance.Design.Error">  
  35.         <EditText  
  36.             android:layout_width="match_parent"  
  37.             android:layout_height="match_parent"  
  38.             android:imeOptions="actionGo"  
  39.             android:inputType="textPassword"  
  40.             android:hint="输入密码"  
  41.             android:lines="1"  
  42.             />  
  43.   
  44.     </android.support.design.widget.TextInputLayout>  
  45. </android.support.percent.PercentRelativeLayout>  
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.singleinstance.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input"
        app:layout_widthPercent="80%"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        app:errorEnabled="true"
        app:errorTextAppearance="@style/TextAppearance.Design.Error">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:imeOptions="actionGo"
            android:inputType="text"
            android:hint="输入姓名"
            android:lines="1"
            />

    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/input2"
        android:layout_below="@+id/input"
        app:layout_widthPercent="80%"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        app:errorEnabled="true"
        app:errorTextAppearance="@style/TextAppearance.Design.Error">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:imeOptions="actionGo"
            android:inputType="textPassword"
            android:hint="输入密码"
            android:lines="1"
            />

    </android.support.design.widget.TextInputLayout>
</android.support.percent.PercentRelativeLayout>
  1. public void TextInputLayout(){  
  2.         textInputLayout = (TextInputLayout) findViewById(R.id.input);  
  3.         textInputLayout2 = (TextInputLayout) findViewById(R.id.input2);  
  4.         textInputLayout2.getEditText().addTextChangedListener(new TextWatcher() {  
  5.             @Override  
  6.             public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {  
  7.   
  8.             }  
  9.   
  10.             @Override  
  11.             public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {  
  12.                 if (charSequence.length() < 4){  
  13.                     textInputLayout2.setError("必须输入6个字符!");  
  14.                     textInputLayout2.setErrorEnabled(true);  
  15.                 }else {  
  16.                     textInputLayout2.setErrorEnabled(false);}  
  17.             }  
  18.   
  19.             @Override  
  20.             public void afterTextChanged(Editable editable) {  
  21.   
  22.             }  
  23.         });  
  24.         textInputLayout.getEditText().addTextChangedListener(new TextWatcher() {  
  25.             @Override  
  26.             public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {  
  27.   
  28.             }  
  29.   
  30.             @Override  
  31.             public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {  
  32.                 if (charSequence.length() < 4){  
  33.                     textInputLayout.setError("必须输入4个字符!");  
  34.                     textInputLayout.setErrorEnabled(true);  
  35.                 }else {  
  36.                     textInputLayout.setErrorEnabled(false);}  
  37.             }  
  38.   
  39.             @Override  
  40.             public void afterTextChanged(Editable editable) {  
  41.   
  42.             }  
  43.         });  
  44.     }  
public void TextInputLayout(){
        textInputLayout = (TextInputLayout) findViewById(R.id.input);
        textInputLayout2 = (TextInputLayout) findViewById(R.id.input2);
        textInputLayout2.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() < 4){
                    textInputLayout2.setError("必须输入6个字符!");
                    textInputLayout2.setErrorEnabled(true);
                }else {
                    textInputLayout2.setErrorEnabled(false);}
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        textInputLayout.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() < 4){
                    textInputLayout.setError("必须输入4个字符!");
                    textInputLayout.setErrorEnabled(true);
                }else {
                    textInputLayout.setErrorEnabled(false);}
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

3.TabLayout

TabLayout控件用于应用中轻松的添加Tab分组功能,总共有两种类型可选。

1.固定的Tabs:对应的xml配置中的 app:tabMode="fixed"

2.可滑动的Tabs:对应xml配置中的 app:tabMode="scrollable"。

TabLayout,它就可以完成TabPageIndicator的效果,而且还是官方的,最好的是它可以兼容到2.2以上版本,包括2.2。接下来就简单使用一下。

先来布局:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     android:id="@+id/activity_tab_layout"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     tools:context="com.example.administrator.designtest.TabLayoutActivity">  
  9.   
  10.     <android.support.v4.view.ViewPager  
  11.         android:id="@+id/viewpager"  
  12.         android:layout_below="@+id/tablayout_top"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="match_parent">  
  15.     </android.support.v4.view.ViewPager>  
  16.   
  17.     <android.support.design.widget.TabLayout  
  18.         android:id="@+id/tablayout_top"  
  19.         app:tabTextColor="#000"  
  20.         app:tabSelectedTextColor="#fff"  
  21.         android:background="@color/colorPrimary"  
  22.         android:layout_width="match_parent"  
  23.         android:layout_height="wrap_content"  
  24.         app:tabMode="fixed"  
  25.         app:tabGravity="fill">  
  26.   
  27.     </android.support.design.widget.TabLayout>  
  28. </RelativeLayout>  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_tab_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.designtest.TabLayoutActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_below="@+id/tablayout_top"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout_top"
        app:tabTextColor="#000"
        app:tabSelectedTextColor="#fff"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill">

    </android.support.design.widget.TabLayout>
</RelativeLayout>
这个很简单,再来一个适配器。

  1. public class ViewPagerAdapter extends FragmentPagerAdapter {  
  2.     private List<BlankFragment>fragmentList;  
  3.     private List<String>titleList;  
  4.     public ViewPagerAdapter(FragmentManager fm, List<BlankFragment> fragmentList, List<String> titleList) {  
  5.         super(fm);  
  6.         this.fragmentList = fragmentList;  
  7.         this.titleList = titleList;  
  8.     }  
  9.   
  10.     @Override  
  11.     public Fragment getItem(int position) {  
  12.         return fragmentList.get(position);  
  13.     }  
  14.   
  15.     @Override  
  16.     public int getCount() {  
  17.         return fragmentList.size();  
  18.     }  
  19.   
  20.     @Override  
  21.     public CharSequence getPageTitle(int position) {  
  22.         return titleList.get(position);  
  23.     }  
  24. }  
public class ViewPagerAdapter extends FragmentPagerAdapter {
    private List<BlankFragment>fragmentList;
    private List<String>titleList;
    public ViewPagerAdapter(FragmentManager fm, List<BlankFragment> fragmentList, List<String> titleList) {
        super(fm);
        this.fragmentList = fragmentList;
        this.titleList = titleList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
}
用过viewpager套Fragement的猿友都知道,就不啰嗦了。getPageTitle是获取需要显示的tab标题。新建一个fragment空的。

  1. public class BlankFragment extends Fragment {  
  2.     @Override  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  4.                              Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment_blank, container, false);  
  6.     }  
  7. }  
public class BlankFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
}
那么准备工作差不多了,开始进入主题,基本的介绍都加了注释

  1. public class TabLayoutActivity extends AppCompatActivity {  
  2.   
  3.     ViewPager viewPager;  
  4.     TabLayout tabLayout;  
  5.   
  6.     List<BlankFragment>fragmentList;  
  7.     List<String>stringList;  
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.activity_tab_layout);  
  13.         viewPager = (ViewPager) findViewById(R.id.viewpager);  
  14.         tabLayout = (TabLayout) findViewById(R.id.tablayout_top);  
  15.         //添加fragment  
  16.         fragmentList = new ArrayList<>();  
  17.         fragmentList.add(new BlankFragment());  
  18.         fragmentList.add(new BlankFragment());  
  19.         fragmentList.add(new BlankFragment());  
  20.         fragmentList.add(new BlankFragment());  
  21.         //添加标题  
  22.         stringList = new ArrayList<>();  
  23.         stringList.add("热门新闻");  
  24.         stringList.add("热门推荐");  
  25.         stringList.add("本月热榜");  
  26.         stringList.add("今日热榜");  
  27.         //添加tab  
  28.         tabLayout.addTab(tabLayout.newTab().setText("热门新闻"));  
  29.         tabLayout.addTab(tabLayout.newTab().setText("热门推荐"));  
  30.         tabLayout.addTab(tabLayout.newTab().setText("本月热榜"));  
  31.         tabLayout.addTab(tabLayout.newTab().setText("今日热榜"));  
  32.         //适配器  
  33.         ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragmentList,stringList);  
  34.         //建立联系  
  35.         viewPager.setAdapter(viewPagerAdapter);  
  36.         tabLayout.setupWithViewPager(viewPager,true);  
  37.     }  
  38. }  
public class TabLayoutActivity extends AppCompatActivity {

    ViewPager viewPager;
    TabLayout tabLayout;

    List<BlankFragment>fragmentList;
    List<String>stringList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tablayout_top);
        //添加fragment
        fragmentList = new ArrayList<>();
        fragmentList.add(new BlankFragment());
        fragmentList.add(new BlankFragment());
        fragmentList.add(new BlankFragment());
        fragmentList.add(new BlankFragment());
        //添加标题
        stringList = new ArrayList<>();
        stringList.add("热门新闻");
        stringList.add("热门推荐");
        stringList.add("本月热榜");
        stringList.add("今日热榜");
        //添加tab
        tabLayout.addTab(tabLayout.newTab().setText("热门新闻"));
        tabLayout.addTab(tabLayout.newTab().setText("热门推荐"));
        tabLayout.addTab(tabLayout.newTab().setText("本月热榜"));
        tabLayout.addTab(tabLayout.newTab().setText("今日热榜"));
        //适配器
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragmentList,stringList);
        //建立联系
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager,true);
    }
}
tabLayout.setupWithViewPager(viewPager,true);这句代码是关联viewpager和tabLayout。后面的true是是否自动刷新fragment的布尔值,看源码就知道了。

  1. public void setupWithViewPager(@Nullable final ViewPager viewPager, boolean autoRefresh) {  
  2.         setupWithViewPager(viewPager, autoRefresh, false);  
  3.     }  
  4.   
  5.     private void setupWithViewPager(@Nullable final ViewPager viewPager, boolean autoRefresh,  
  6.             boolean implicitSetup) {  
  7.         ......  
  8.         //这里需要先设置viewpager的adapter,在关联,不然这里判空不会走正常逻辑  
  9.             if (adapter != null) {  
  10.                 // Now we'll populate ourselves from the pager adapter, adding an observer if  
  11.                 // autoRefresh is enabled  
  12.                 setPagerAdapter(adapter, autoRefresh);  
  13.             }  
  14.   
  15.             if (mAdapterChangeListener == null) {  
  16.                 mAdapterChangeListener = new AdapterChangeListener();  
  17.             }  
  18.             //设置自动刷新  
  19.             mAdapterChangeListener.setAutoRefresh(autoRefresh);  
  20.             viewPager.addOnAdapterChangeListener(mAdapterChangeListener);  
  21.   
  22.               
  23.             setScrollPosition(viewPager.getCurrentItem(), 0f, true);  
  24.           
  25.         ......  
  26.   
  27.         mSetupViewPagerImplicitly = implicitSetup;  
  28.     }  
public void setupWithViewPager(@Nullable final ViewPager viewPager, boolean autoRefresh) {
        setupWithViewPager(viewPager, autoRefresh, false);
    }

    private void setupWithViewPager(@Nullable final ViewPager viewPager, boolean autoRefresh,
            boolean implicitSetup) {
        ......
		//这里需要先设置viewpager的adapter,在关联,不然这里判空不会走正常逻辑
            if (adapter != null) {
                // Now we'll populate ourselves from the pager adapter, adding an observer if
                // autoRefresh is enabled
                setPagerAdapter(adapter, autoRefresh);
            }

            if (mAdapterChangeListener == null) {
                mAdapterChangeListener = new AdapterChangeListener();
            }
			//设置自动刷新
            mAdapterChangeListener.setAutoRefresh(autoRefresh);
            viewPager.addOnAdapterChangeListener(mAdapterChangeListener);

            
            setScrollPosition(viewPager.getCurrentItem(), 0f, true);
        
		......

        mSetupViewPagerImplicitly = implicitSetup;
    }
我们调用的第一个函数,实质是调用的第二个函数。这里需要注意的是需要先调用viewpager的setAdaper之后才能把tabLayout和viewpager关联起来。给个效果图(由于电脑跑不起模拟器,用的真机,所以只能截图,还得多担待)


4.NavigationView

以前做侧边栏的有SlideMenu三方库,这里不详细介绍了,想要了解的给个链接: http://blog.csdn.net/luck_apple/article/details/9207811。现在有了NavigationView官方提供的,当然都渐渐使用这个了。官网地址也给出来,有空的可以去瞅瞅: http://www.google.com/design/spec/patterns/navigation-drawer.html

使用导航视图需要传入一组参数,一个可选的头部布局,以及一个用于构建导航选项的菜单,完成这些步骤以后只需给导航选项添加响应事件的监听器就可以了。

在使用NavigationView时需要提前准备好两个xml文件,一个是头布局,一个是menu布局。menu的一些属性值是干嘛的,我相信有的猿友不是很清楚、下面简单介绍一下。

   4.1 menu属性值介绍

元素(ELEMENTS):

<menu>

必须的。它必须是根节点,其中要包含<item><group>元素。

属性(ATTRIBUTES):

    xmlns:android

    它定义了XML的命名空间,必须是:http://schemas.android.com/apk/res/android

<item>

它定义一个菜单项,可以包含一个<menu>元素作为子菜单。它必须是<menu><group>元素的子元素。

属性(ATTRIBUTES):

    android:id

    定义资源ID,它是个唯一值,使用“@+id/name”格式可以给这个菜单项创建一个新的资源ID,“+”号指示要创建一个新的ID

    android:title

    字符串资源,它用字符串资源或原始的字符串来定义菜单的标题。

    android:titleCondensed

    字符串资源。它用字符串资源或原始的字符串来定义一个简要的标题,以便在普通的标题太长时来使用。

    android:icon

    可绘制资源,它定义了一个菜单项所要使用的图标。

    android:onClick

    方法名。在这个菜单项被点击时,会调用这个方法。在Activity中,这个方法必须用public关键字来声明,并且只接受一个MenuItem对象,这个对象指明了被点击的菜单项。这个方法会优先标准的回调方法:onOptionsItemSelected()

    警告:如果要使用ProGuard(或类似的工具)来混淆代码,就要确保不要重名这个属性所指定的方法,因为这样能够破坏功能。

    这个属性在API级别11中被引入。

    android:showAsAction

    关键词。它定义这个项目作为操作栏中的操作项的显示时机和方式。只用Activity包含了一个ActionBar对象时,菜单项才能够作为操作项来显示。这个属性在API级别11中被引入,有效值如下:

说明

ifRoom

如果有针对这个项目的空间,则只会把它放到操作栏中

withText

操作项也要包含文本(通过android:title属性来定义的)。可以把这个值与其他的Flag设置放到一起,通过管道符“|”来分离它们。

never

这个项目不会放到操作栏中

always

始终包这个项目放到操作栏中。要避免使用这个设置,除非在操作栏中始终显示这个项目是非常关键的。设置多个项目作为始终显示的操作项会导致操作栏中其他的UI溢出。

icollapseActiionView

它定义了跟这个操作项关联的可折叠的操作View对象(用android:actionViewLayout来声明)。这个关键词在API级别14中被引入。

 

这个属性在API级别11中被引入。

    android:actionViewLayout

    它引用一个布局资源,这个布局要用于操作窗口。更多的信息请参照“操作栏”开发指南。这个属性在API级别11中被引入。(http://blog.csdn.net/fireofstar/article/details/7358393

    android:actionViewClass

    类名。它定义了操作窗口要使用的View对象的完整的类名。例如,“android.widget.SearchView”说明操作窗口要使用的SearchView类。

    警告:如果要使用ProGuard(或类似的工具)来混淆代码,就要确保不要重名这个属性所指定的方法,因为这样能够破坏功能。

     这个属性在API级别11中被引入。

    android:actionProviderClass

    类名,它是操作项目所使用的ActionProvider类的完整的类名。例如,“android.widget.ShareActionProvider”说明要使用ShareActionProvider类。

警告:如果要使用ProGuard(或类似的工具)来混淆代码,就要确保不要重名这个属性所指定的方法,因为这样能够破坏功能。

    这个属性在API级别14中被引入。

    android:alphabeticShortcut

    字符,定义一个字符快捷键

    android:numericShortcut

    数字值,定义一个数字快捷键

    android:checkable

    布尔值,如果菜单项是可以复选的,那么就设置为true

    android:checked

    布尔值,如果复选菜单项默认是被选择的,那么就设置为true

    android:visible

    布尔值,如果菜单项默认是可见的,那么就设置为true

    android:enabled

    布尔值,如果菜单项目默认是可用的,那么就设置为true

    android:menuCategory

    关键词。它的值对应了定义菜单项优先级的CATEGORE_*常量,有效值如下:

说明

Container

菜单项是容器的一部分

system

菜单项是由系统提供的。

secondary

提供给用户的辅助选择的菜单项(很少使用)

alternative

基于当前显示的数据来选择操作的菜单项。

    android:orderInCategory

    整数值,它定义菜单项在菜单组中的重要性的顺序。

 

<group>

它定义了一个菜单组(它是一个具有共同特征的菜单项的组合,如菜单项的可见性、可用性或可复选性)。它要包含多个<item>元素,而且必须是<menu>元素的子元素。

    属性(ATTRIBUTES):

    android:id

    资源ID。它是资源的唯一标识。使用“@+id/name”格式给菜单项创建一个新的资源ID。“+”号指示应该给这个元素创建一个新的资源ID

    android:checkableBeharior

    关键词。针对菜单组的可复选行为的类型。有效值如下:

说明

none

没有可复选性

all

组内的所有的项目都被复选(使用复选框)

single

仅有一个项目能够被复选(使用单选按钮)

    android:visible

    布尔值,如果菜单组是可见的,就设置为true

    android:enabled

    布尔值,如果菜单组是可用的,就设置为true

    android:menuCategory

    关键词。它的值对应了Menu类的CATEGORY_*常量,定义了菜单组的优先级。有效值如下:

说明

container

菜单组是容器的一部分

system

菜单组是由系统提供的。

secondary

提供给用户的辅助选择的菜单组(很少使用)

alternative

基于当前显示的数据来选择操作的菜单组。

    android:orderInCategory

    整数值,它定义了分类中菜单项目的默认顺序。差不多就这些了,在res文件夹下创建一个名为menu的文件夹存放menu的xml文件。取名为draw_view.xml。

  1. <menu xmlns:app="http://schemas.android.com/apk/res-auto"  
  2.     xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <group android:checkableBehavior="single">  
  4.         <item  
  5.             android:id="@+id/nav_home"  
  6.             android:icon="@drawable/center_image_collection"  
  7.             android:title="Home"/>  
  8.         <item  
  9.             android:id="@+id/nav_messages"  
  10.             android:icon="@drawable/center_message"  
  11.             android:title="Messages"/>  
  12.         <item  
  13.             android:id="@+id/nav_friends"  
  14.             android:icon="@drawable/center_reading_collection"  
  15.             android:title="Friends"/>  
  16.         <item  
  17.             android:id="@+id/nav_discussion"  
  18.             android:icon="@drawable/center_night_mode"  
  19.             android:title="Discussion"/>  
  20.     </group>  
  21.     <item android:title="Sub items">  
  22.         <menu>  
  23.             <item  
  24.                 android:id="@+id/sub1"  
  25.                 android:icon="@drawable/center_setting"  
  26.                 android:title="Sub item 1"  
  27.                 />  
  28.             <item  
  29.                 android:id="@+id/sub2"  
  30.                 android:icon="@drawable/center_movie_collection"  
  31.                 android:title="Sub item 2"  
  32.                 />  
  33.         </menu>  
  34.     </item>  
  35. </menu>  
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/center_image_collection"
            android:title="Home"/>
        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/center_message"
            android:title="Messages"/>
        <item
            android:id="@+id/nav_friends"
            android:icon="@drawable/center_reading_collection"
            android:title="Friends"/>
        <item
            android:id="@+id/nav_discussion"
            android:icon="@drawable/center_night_mode"
            android:title="Discussion"/>
    </group>
    <item android:title="Sub items">
        <menu>
            <item
                android:id="@+id/sub1"
                android:icon="@drawable/center_setting"
                android:title="Sub item 1"
                />
            <item
                android:id="@+id/sub2"
                android:icon="@drawable/center_movie_collection"
                android:title="Sub item 2"
                />
        </menu>
    </item>
</menu>


在创建一个头布局,命名为nav_header.xml。

  1. <LinearLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="192dp"  
  6.     android:paddingTop="30dp"  
  7.     android:paddingLeft="16dp"  
  8.     android:background="@color/colorPrimaryDark"  
  9.     android:theme="@style/ThemeOverlay.AppCompat.Dark"  
  10.     android:gravity="center|left">  
  11.   
  12.     <ImageView  
  13.         android:id="@+id/avatar"  
  14.         android:layout_width="64dp"  
  15.         android:layout_height="64dp"  
  16.         android:scaleType="centerCrop"  
  17.         android:src="@drawable/a"  
  18.         />  
  19.   
  20.     <TextView  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_marginTop="10dp"  
  24.         android:textAppearance="@style/TextAppearance.AppCompat.Body1"  
  25.         android:text="鬼刀z六极之首"  
  26.         android:id="@+id/textView" />  
  27.   
  28.   
  29. </LinearLayout>  
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:paddingTop="30dp"
    android:paddingLeft="16dp"
    android:background="@color/colorPrimaryDark"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:gravity="center|left">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:scaleType="centerCrop"
        android:src="@drawable/a"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:text="鬼刀z六极之首"
        android:id="@+id/textView" />


</LinearLayout>


好了,成功了一半,那么现在需要在主xml文件中布局,使用navigationView最外层是需要DrawerLayout的。

  1. <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     android:id="@+id/activity_navigation"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:fitsSystemWindows="true"  
  8.     tools:context="com.example.administrator.designtest.NavigationActivity">  
  9.   
  10.     <LinearLayout  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:orientation="vertical">  
  14.   
  15.         <android.support.v7.widget.Toolbar  
  16.             android:id="@+id/id_toolbar"  
  17.             android:layout_width="match_parent"  
  18.             android:layout_height="?attr/actionBarSize"  
  19.             android:background="?attr/colorPrimary"  
  20.             app:layout_scrollFlags="scroll|enterAlways"  
  21.             app:popupTheme="@style/ThemeOverlay.AppCompat.Light"  
  22.             app:title=" 魔尊重楼" />  
  23.   
  24.         <FrameLayout  
  25.             android:id="@+id/content"  
  26.             android:layout_width="match_parent"  
  27.             android:layout_height="match_parent">  
  28.   
  29.         </FrameLayout>  
  30.     </LinearLayout>  
  31.   
  32.     <android.support.percent.PercentRelativeLayout  
  33.         android:fitsSystemWindows="true"  
  34.         android:layout_gravity="start"  
  35.         android:layout_width="match_parent"  
  36.         android:layout_height="match_parent">  
  37.         <android.support.design.widget.NavigationView  
  38.             android:id="@+id/nav_view"  
  39.             android:layout_width="0dp"  
  40.             app:layout_widthPercent="80%"  
  41.             android:layout_height="match_parent"  
  42.             app:headerLayout="@layout/nav_header"  
  43.             app:menu="@menu/draw_view">  
  44.   
  45.         </android.support.design.widget.NavigationView>  
  46.     </android.support.percent.PercentRelativeLayout>  
  47.   
  48.   
  49.   
  50. </android.support.v4.widget.DrawerLayout>  
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.administrator.designtest.NavigationActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/id_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:title=" 魔尊重楼" />

        <FrameLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
    </LinearLayout>

    <android.support.percent.PercentRelativeLayout
        android:fitsSystemWindows="true"
        android:layout_gravity="start"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="0dp"
            app:layout_widthPercent="80%"
            android:layout_height="match_parent"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/draw_view">

        </android.support.design.widget.NavigationView>
    </android.support.percent.PercentRelativeLayout>



</android.support.v4.widget.DrawerLayout>


这里我使用了一下百分比布局,防止有的产品经理有侧滑栏占屏幕的百分之多少多少之类的要求。
  1. public class NavigationActivity extends AppCompatActivity {  
  2.   
  3.     Toolbar toolbar;  
  4.     DrawerLayout drawerLayout;  
  5.     NavigationView navigationView;  
  6.   
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_navigation);  
  11.         toolbar = (Toolbar) findViewById(R.id.id_toolbar);  
  12.         drawerLayout = (DrawerLayout) findViewById(R.id.activity_navigation);  
  13.         navigationView = (NavigationView) findViewById(R.id.nav_view);  
  14.         //<activity android:name=".NavigationActivity" android:theme="@style/AppThemeNoActionBar"></activity>  
  15.         //<style name="AppThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">  
  16.         //初始化toolbar,这里得使用NoActionBar的主题,使用ToolBar替换系统自带的ActionBar达到自己的需求  
  17.         setSupportActionBar(toolbar);  
  18.         ActionBar actionBar = getSupportActionBar();  
  19.         //关联图标和侧滑栏  
  20.         actionBar.setHomeAsUpIndicator(R.drawable.center_image_collection);  
  21.         //设置actionBar和侧滑栏关联  
  22.         actionBar.setDisplayHomeAsUpEnabled(true);  
  23.         //初始化drawerlayout和navigationview  
  24.         if (navigationView != null){  
  25.             //设置监听回调  
  26.             navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {  
  27.                 @Override  
  28.                 public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
  29.                     //根据选中不同的选项来进行不同的操作  
  30.                     switch (item.getItemId()){  
  31.                         case R.id.nav_home:  
  32.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("主页")).commit();  
  33.                             toolbar.setTitle("主页");  
  34.                             break;  
  35.                         case R.id.nav_friends:  
  36.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("我的好友")).commit();  
  37.                             toolbar.setTitle("我的好友");  
  38.                             break;  
  39.                         case R.id.nav_discussion:  
  40.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("热文论坛")).commit();  
  41.                             toolbar.setTitle("热文论坛");  
  42.                             break;  
  43.                         case R.id.nav_messages:  
  44.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("我的消息")).commit();  
  45.                             toolbar.setTitle("我的消息");  
  46.                             break;  
  47.                         case R.id.sub1:  
  48.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("子项1")).commit();  
  49.                             toolbar.setTitle("子项1");  
  50.                             break;  
  51.                         case R.id.sub2:  
  52.                             getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("子项2")).commit();  
  53.                             toolbar.setTitle("子项2");  
  54.                             break;  
  55.                     }  
  56.                     //设置选项选中效果  
  57.                     item.setChecked(true);  
  58.                     //选了侧边栏选项之后,关闭侧边栏  
  59.                     drawerLayout.closeDrawers();  
  60.                     //这里返回true有选中的效果,源码中有解释  
  61.                     return true;  
  62.                 }  
  63.             });  
  64.         }  
  65.   
  66.     }  
  67.   
  68.     @Override  
  69.     public boolean onOptionsItemSelected(MenuItem item) {  
  70.         switch (item.getItemId()){  
  71.             //点击左上角的菜单选项,这是在actionBar.setHomeAsUpIndicator(R.drawable.center_image_collection);这儿设置的。  
  72.             case android.R.id.home:  
  73.                 //点击之后打开侧滑栏  
  74.                 drawerLayout.openDrawer(GravityCompat.START);  
  75.                 return true;  
  76.         }  
  77.         return super.onOptionsItemSelected(item);  
  78.     }  
  79. }  
public class NavigationActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayout;
    NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_navigation);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        //<activity android:name=".NavigationActivity" android:theme="@style/AppThemeNoActionBar"></activity>
        //<style name="AppThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
        //初始化toolbar,这里得使用NoActionBar的主题,使用ToolBar替换系统自带的ActionBar达到自己的需求
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //关联图标和侧滑栏
        actionBar.setHomeAsUpIndicator(R.drawable.center_image_collection);
        //设置actionBar和侧滑栏关联
        actionBar.setDisplayHomeAsUpEnabled(true);
        //初始化drawerlayout和navigationview
        if (navigationView != null){
            //设置监听回调
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    //根据选中不同的选项来进行不同的操作
                    switch (item.getItemId()){
                        case R.id.nav_home:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("主页")).commit();
                            toolbar.setTitle("主页");
                            break;
                        case R.id.nav_friends:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("我的好友")).commit();
                            toolbar.setTitle("我的好友");
                            break;
                        case R.id.nav_discussion:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("热文论坛")).commit();
                            toolbar.setTitle("热文论坛");
                            break;
                        case R.id.nav_messages:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("我的消息")).commit();
                            toolbar.setTitle("我的消息");
                            break;
                        case R.id.sub1:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("子项1")).commit();
                            toolbar.setTitle("子项1");
                            break;
                        case R.id.sub2:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,BlankFragment.newInstance("子项2")).commit();
                            toolbar.setTitle("子项2");
                            break;
                    }
                    //设置选项选中效果
                    item.setChecked(true);
                    //选了侧边栏选项之后,关闭侧边栏
                    drawerLayout.closeDrawers();
                    //这里返回true有选中的效果,源码中有解释
                    return true;
                }
            });
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            //点击左上角的菜单选项,这是在actionBar.setHomeAsUpIndicator(R.drawable.center_image_collection);这儿设置的。
            case android.R.id.home:
                //点击之后打开侧滑栏
                drawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

一些详细的介绍都写在了注释里,若还是有什么不懂的,可以参考这篇博客:http://blog.csdn.net/lamp_zy/article/details/50126531,介绍的比较详细。NavigationView就到这儿了。下一个Design库里的。


5.FloatingActionButton

浮动操作按钮实在Material Design准则中新引入的组件。用于强调当前屏幕最重要,高频率的一些操作。

FloatingActionButton正常显示的情况下有个填充的颜色,有个阴影;点击的时候会有一个rippleColor,并且阴影的范围可以增大,那么问题来了:

  • 这个填充色以及rippleColor如何自定义呢?

    默认的颜色取的是,theme中的colorAccent,所以你可以在style中定义colorAccent。

    colorAccent 对应EditText编辑时、RadioButton选中、CheckBox等选中时的颜色。详细请参考:Android 5.x Theme 与 ToolBar 实战

    rippleColor默认取的是theme中的colorControlHighlight。

    我们也可以直接用过属性定义这两个的颜色:

    app:backgroundTint="#ff87ffeb"
    app:rippleColor="#33728dff"
        
        
    • 1
    • 2
    • 1
    • 2
  • 立体感有没有什么属性可以动态指定?

    和立体感相关有两个属性,elevation和pressedTranslationZ,前者用户设置正常显示的阴影大小;后者是点击时显示的阴影大小。大家可以自己设置尝试下。

在5.x的设备上运行,你会发现一些问题(测试系统5.0):

  • 木有阴影

记得设置app:borderWidth="0dp"

  • 按上述设置后,阴影出现了,但是竟然有矩形的边界(未设置margin时,可以看出)

需要设置一个margin的值。在5.0之前,会默认就有一个外边距(不过并非是margin,只是效果相同)。

so,良好的实践是:

  • 添加属性app:borderWidth="0dp"
  • 对于5.x设置一个合理的margin
写一个简单的使用例子。

  1. <android.support.design.widget.FloatingActionButton  
  2.        android:id="@+id/floatingaction"  
  3.        android:onClick="designClick"  
  4.        android:layout_width="wrap_content"  
  5.        android:layout_height="wrap_content"  
  6.        app:elevation="3dp"  
  7.        app:rippleColor="@color/colorAccent"  
  8.        app:borderWidth="0dp"  
  9.        android:backgroundTint="@color/colorPrimary"  
  10.        app:pressedTranslationZ="6dp"  
  11.        android:layout_margin="12dp"  
  12.        android:src="@mipmap/ic_launcher"  
  13.        android:layout_alignParentBottom="true"  
  14.        android:layout_alignParentRight="true"  
  15.        />  
 <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingaction"
        android:onClick="designClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:elevation="3dp"
        app:rippleColor="@color/colorAccent"
        app:borderWidth="0dp"
        android:backgroundTint="@color/colorPrimary"
        app:pressedTranslationZ="6dp"
        android:layout_margin="12dp"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        />
由于没办法运行模拟器,就上个图片吧,app:rippleColor这个是点击颜色,android:backgroundTint这个是显示背景颜色。会有一个渐变的过程,可以试试。也可以参考鸿神的一篇介绍: http://blog.csdn.net/lmj623565791/article/details/46678867


6.CoordinatorLayout

CoordinatorLayout是Design引入的一个功能强大的布局,本质上是一个增强的FrameLayout,它可以使得不同组件之间直接相互作用,并协调动画效果。我们可以定义CoordinatorLayout内部的视图组件如何相互作用并发生变化。例如刚才的FloatingActionButton 和 SnackBar,为了实现SnackBar出现时FAB能够上移,我们可以使用CoordinatorLayout为父容器。

  1. <android.support.design.widget.CoordinatorLayout  
  2.         android:id="@+id/coordinator"  
  3.         android:layout_height="match_parent"  
  4.         android:layout_width="match_parent"  
  5.         android:layout_alignParentBottom="true">  
  6.         <android.support.design.widget.FloatingActionButton  
  7.             android:id="@+id/floatingaction"  
  8.             android:onClick="designClick"  
  9.             android:layout_width="wrap_content"  
  10.             android:layout_height="wrap_content"  
  11.             app:elevation="3dp"  
  12.             app:rippleColor="@color/colorAccent"  
  13.             app:borderWidth="0dp"  
  14.             android:backgroundTint="@color/colorPrimary"  
  15.             app:pressedTranslationZ="6dp"  
  16.             android:layout_margin="12dp"  
  17.             android:src="@mipmap/ic_launcher"  
  18.             android:layout_gravity="right|bottom"  
  19.             />  
  20.     </android.support.design.widget.CoordinatorLayout>  
<android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinator"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_alignParentBottom="true">
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/floatingaction"
            android:onClick="designClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:elevation="3dp"
            app:rippleColor="@color/colorAccent"
            app:borderWidth="0dp"
            android:backgroundTint="@color/colorPrimary"
            app:pressedTranslationZ="6dp"
            android:layout_margin="12dp"
            android:src="@mipmap/ic_launcher"
            android:layout_gravity="right|bottom"
            />
    </android.support.design.widget.CoordinatorLayout>
然后在代码中,把Coordinator给SnackBar.

  1. Snackbar.make(coordinatorLayout,"点击了floatingActionButton",Snackbar.LENGTH_LONG).show();  
 Snackbar.make(coordinatorLayout,"点击了floatingActionButton",Snackbar.LENGTH_LONG).show();
这样就实现了简单的动画联动。这个是最简单的使用,等一下学了CollapsingToolbarLayout和AppbarLayout配合起来更华丽。


7.CollapsingToolbarLayout
CollapsingToolbarLayout控件可以实现当屏幕内容滚动时收缩Toolbar的效果,通常配合AppBarLayout一起使用。

先看看toolbar的一些区域划分

有了这图就知道我们该设置toolbar里的什么位置了。

CollapsingToolbarLayout 提供以下属性和方法是用: 
1. Collapsing title:ToolBar的标题,当CollapsingToolbarLayout全屏没有折叠时,title显示的是大字体,在折叠的过程中,title不断变小到一定大小的效果。你可以调用setTitle(CharSequence)方法设置title。 
2. Content scrim:ToolBar被折叠到顶部固定时候的背景,你可以调用setContentScrim(Drawable)方法改变背景或者 在属性中使用 app:contentScrim=”?attr/colorPrimary”来改变背景。 
3. Status bar scrim:状态栏的背景,调用方法setStatusBarScrim(Drawable)。还没研究明白,不过这个只能在Android5.0以上系统有效果。 
4. Parallax scrolling children:CollapsingToolbarLayout滑动时,子视图的视觉差,可以通过属性app:layout_collapseParallaxMultiplier=”0.6”改变。值de的范围[0.0,1.0],值越大视察越大。 
5. CollapseMode :子视图的折叠模式,在子视图设置,有两种“pin”:固定模式,在折叠的时候最后固定在顶端;“parallax”:视差模式,在折叠的时候会有个视差折叠的效果。我们可以在布局中使用属性app:layout_collapseMode=”parallax”来改变。


CoordinatorLayout 还提供了一个 layout_anchor 的属性,连同 layout_anchorGravity 一起,可以用来放置与其他视图关联在一起的悬浮视图(如 FloatingActionButton)

使用CollapsingToolbarLayout实现折叠效果,需要注意3点 。
1. AppBarLayout的高度固定 
2. CollapsingToolbarLayout的子视图设置layout_collapseMode属性 
3. 关联悬浮视图设置app:layout_anchor,app:layout_anchorGravity属性

那么先写一个xml。

  1. <android.support.design.widget.CoordinatorLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     android:id="@+id/activity_collasping"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     android:fitsSystemWindows="true"  
  9.     tools:context="com.example.administrator.designtest.CollaspingActivity">  
  10.   
  11.     <android.support.design.widget.AppBarLayout  
  12.         android:id="@+id/appbar"  
  13.         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
  14.         android:fitsSystemWindows="true"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content">  
  17.         <android.support.design.widget.CollapsingToolbarLayout  
  18.             android:id="@+id/collasping_toolbar"  
  19.             android:layout_width="match_parent"  
  20.             android:layout_height="match_parent"  
  21.             android:fitsSystemWindows="true"  
  22.             app:contentScrim="?attr/colorPrimary"  
  23.             app:title="鬼刀"  
  24.             app:layout_collapseParallaxMultiplier="0.6"  
  25.             app:layout_scrollFlags="scroll|exitUntilCollapsed">  
  26.   
  27.             <ImageView  
  28.                 android:id="@+id/backdrop"  
  29.                 android:background="@drawable/a"  
  30.                 android:layout_width="match_parent"  
  31.                 android:layout_height="256dp"  
  32.                 android:fitsSystemWindows="true"  
  33.                 android:scaleType="centerCrop"  
  34.                 app:layout_collapseMode="parallax"/>  
  35.   
  36.             <android.support.v7.widget.Toolbar  
  37.                 android:id="@+id/toolbar"  
  38.                 app:navigationIcon="@mipmap/ic_launcher"  
  39.                 android:layout_width="match_parent"  
  40.                 android:layout_height="?attr/actionBarSize"  
  41.                 app:layout_collapseMode="pin"  
  42.                 app:titleTextColor="#fff"  
  43.                 android:popupTheme="@style/ThemeOverlay.AppCompat.Light">  
  44.   
  45.             </android.support.v7.widget.Toolbar>  
  46.         </android.support.design.widget.CollapsingToolbarLayout>  
  47.     </android.support.design.widget.AppBarLayout>  
  48.   
  49.   
  50.     <android.support.v4.widget.NestedScrollView  
  51.         android:layout_width="match_parent"  
  52.         android:layout_height="match_parent"  
  53.         app:layout_behavior="@string/appbar_scrolling_view_behavior">  
  54.   
  55.         <LinearLayout  
  56.             android:layout_width="match_parent"  
  57.             android:layout_height="match_parent"  
  58.             android:orientation="vertical"  
  59.             android:paddingTop="14dp">  
  60.   
  61.             <android.support.v7.widget.CardView  
  62.                 android:layout_width="match_parent"  
  63.                 android:layout_height="100dp"  
  64.                 android:background="@drawable/music_board"  
  65.                 android:layout_margin="16dp">  
  66.   
  67.                 <LinearLayout  
  68.                     android:orientation="vertical"  
  69.                     android:padding="10dp"  
  70.                     android:layout_width="match_parent"  
  71.                     android:layout_height="wrap_content">  
  72.   
  73.                     <TextView  
  74.                         android:layout_width="match_parent"  
  75.                         android:layout_height="wrap_content"  
  76.                         android:text="CardView"  
  77.                         android:textAppearance="@style/TextAppearance.AppCompat.Title" />  
  78.   
  79.                     <TextView  
  80.                         android:layout_width="match_parent"  
  81.                         android:layout_height="wrap_content"  
  82.                         android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />  
  83.   
  84.                 </LinearLayout>  
  85.   
  86.             </android.support.v7.widget.CardView>  
  87.   
  88.             <android.support.v7.widget.CardView  
  89.                 android:layout_width="match_parent"  
  90.                 android:layout_height="100dp"  
  91.                 android:background="@drawable/music_board"  
  92.                 android:layout_margin="16dp">  
  93.   
  94.                 <LinearLayout  
  95.                     android:orientation="vertical"  
  96.                     android:padding="10dp"  
  97.                     android:layout_width="match_parent"  
  98.                     android:layout_height="wrap_content">  
  99.   
  100.                     <TextView  
  101.                         android:layout_width="match_parent"  
  102.                         android:layout_height="wrap_content"  
  103.                         android:text="CardView"  
  104.                         android:textAppearance="@style/TextAppearance.AppCompat.Title" />  
  105.   
  106.                     <TextView  
  107.                         android:layout_width="match_parent"  
  108.                         android:layout_height="wrap_content"  
  109.                         android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />  
  110.   
  111.                 </LinearLayout>  
  112.   
  113.             </android.support.v7.widget.CardView>  
  114.   
  115.             <android.support.v7.widget.CardView  
  116.                 android:layout_width="match_parent"  
  117.                 android:layout_height="100dp"  
  118.                 android:background="@drawable/music_board"  
  119.                 android:layout_margin="16dp">  
  120.   
  121.                 <LinearLayout  
  122.                     android:orientation="vertical"  
  123.                     android:padding="10dp"  
  124.                     android:layout_width="match_parent"  
  125.                     android:layout_height="wrap_content">  
  126.   
  127.                     <TextView  
  128.                         android:layout_width="match_parent"  
  129.                         android:layout_height="wrap_content"  
  130.                         android:text="CardView"  
  131.                         android:textAppearance="@style/TextAppearance.AppCompat.Title" />  
  132.   
  133.                     <TextView  
  134.                         android:layout_width="match_parent"  
  135.                         android:layout_height="wrap_content"  
  136.                         android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />  
  137.   
  138.                 </LinearLayout>  
  139.   
  140.             </android.support.v7.widget.CardView>  
  141.   
  142.             <android.support.v7.widget.CardView  
  143.                 android:layout_width="match_parent"  
  144.                 android:layout_height="100dp"  
  145.                 android:background="@drawable/music_board"  
  146.                 android:layout_margin="16dp">  
  147.   
  148.                 <LinearLayout  
  149.                     android:orientation="vertical"  
  150.                     android:padding="10dp"  
  151.                     android:layout_width="match_parent"  
  152.                     android:layout_height="wrap_content">  
  153.   
  154.                     <TextView  
  155.                         android:layout_width="match_parent"  
  156.                         android:layout_height="wrap_content"  
  157.                         android:text="CardView"  
  158.                         android:textAppearance="@style/TextAppearance.AppCompat.Title" />  
  159.   
  160.                     <TextView  
  161.                         android:layout_width="match_parent"  
  162.                         android:layout_height="wrap_content"  
  163.                         android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />  
  164.   
  165.                 </LinearLayout>  
  166.   
  167.             </android.support.v7.widget.CardView>  
  168.         </LinearLayout>  
  169.   
  170.     </android.support.v4.widget.NestedScrollView>  
  171.     <android.support.design.widget.FloatingActionButton  
  172.         app:layout_anchor="@id/appbar"  
  173.         app:layout_anchorGravity="bottom|right|end"  
  174.         android:src="@drawable/center_image_collection"  
  175.         android:backgroundTint="@color/colorPrimary"  
  176.         app:borderWidth="0dp"  
  177.         android:layout_margin="12dp"  
  178.         app:rippleColor="@color/colorPrimaryDark"  
  179.         app:elevation="6dp"  
  180.         app:pressedTranslationZ="12dp"  
  181.         android:layout_width="wrap_content"  
  182.         android:layout_height="wrap_content" />  
  183.   
  184. </android.support.design.widget.CoordinatorLayout>  
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_collasping"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.administrator.designtest.CollaspingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collasping_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:title="鬼刀"
            app:layout_collapseParallaxMultiplier="0.6"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:background="@drawable/a"
                android:layout_width="match_parent"
                android:layout_height="256dp"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                app:navigationIcon="@mipmap/ic_launcher"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:titleTextColor="#fff"
                android:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>


    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="14dp">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@drawable/music_board"
                android:layout_margin="16dp">

                <LinearLayout
                    android:orientation="vertical"
                    android:padding="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="CardView"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@drawable/music_board"
                android:layout_margin="16dp">

                <LinearLayout
                    android:orientation="vertical"
                    android:padding="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="CardView"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@drawable/music_board"
                android:layout_margin="16dp">

                <LinearLayout
                    android:orientation="vertical"
                    android:padding="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="CardView"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@drawable/music_board"
                android:layout_margin="16dp">

                <LinearLayout
                    android:orientation="vertical"
                    android:padding="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="CardView"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="this is a cardview ,so so good!\nthis is a cardview ,so so good!\nthis is a cardview ,so so good!" />

                </LinearLayout>

            </android.support.v7.widget.CardView>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/center_image_collection"
        android:backgroundTint="@color/colorPrimary"
        app:borderWidth="0dp"
        android:layout_margin="12dp"
        app:rippleColor="@color/colorPrimaryDark"
        app:elevation="6dp"
        app:pressedTranslationZ="12dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.design.widget.CoordinatorLayout>
直接可以运行了。看看效果咋样


这里的FloatingActionButton会随着AppBarLayout移动,是因为设置了

app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"

8.BottomSheetBehavior

BottomSheetBehavior可以轻松实现底部动作条功能,底部动作条的引入需要在布局添加app:layout_behavior属性,并将这个布局作为CoordianatorLayout的子View。这个可以用于一些从下面弹出选项的操作。


方法 用途
setPeekHeight 偷看的高度;哈,这么理解,就是默认显示后View露头的高度
getPeekHeight @see setPeekHeight()
setHideable 设置是否可以隐藏,如果为true,表示状态可以为STATE_HIDDEN
isHideable @see setHideable()
setState 设置状态;设置不同的状态会影响BottomSheetView的显示效果
getState 获取状态
setBottomSheetCallback 设置状态改变回调

举一个简单的运用

  1. <android.support.design.widget.CoordinatorLayout  
  2.        android:id="@+id/coordinator"  
  3.        android:layout_below="@+id/design_bottom_sheet"  
  4.        android:layout_height="match_parent"  
  5.        android:layout_width="match_parent">  
  6.   
  7.        <LinearLayout  
  8.            android:id="@+id/bottom_sheet"  
  9.            android:orientation="vertical"  
  10.            android:background="#e8e8e8"  
  11.            app:behavior_peekHeight="0dp"  
  12.            app:behavior_hideable="true"  
  13.            android:layout_marginTop="10dp"  
  14.            android:layout_width="match_parent"  
  15.            android:layout_height="200dp"  
  16.            app:layout_behavior="@string/bottom_sheet_behavior">  
  17.   
  18.            <android.support.v7.widget.RecyclerView  
  19.                android:id="@+id/recyclerview"  
  20.                android:layout_width="match_parent"  
  21.                android:layout_height="wrap_content">  
  22.   
  23.            </android.support.v7.widget.RecyclerView>  
  24.   
  25.        </LinearLayout>  
  26.   
  27.        <android.support.design.widget.FloatingActionButton  
  28.            android:id="@+id/floatingaction"  
  29.            android:onClick="designClick"  
  30.            android:layout_width="wrap_content"  
  31.            android:layout_height="wrap_content"  
  32.            app:elevation="3dp"  
  33.            app:rippleColor="@color/colorAccent"  
  34.            app:layout_anchor="@id/bottom_sheet"  
  35.            app:layout_anchorGravity="right|top"  
  36.            app:borderWidth="0dp"  
  37.            android:backgroundTint="@color/colorPrimary"  
  38.            app:pressedTranslationZ="6dp"  
  39.            android:layout_margin="10dp"  
  40.            android:src="@mipmap/ic_launcher"  
  41.            />  
  42.   
  43.    </android.support.design.widget.CoordinatorLayout>  
 <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinator"
        android:layout_below="@+id/design_bottom_sheet"
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <LinearLayout
            android:id="@+id/bottom_sheet"
            android:orientation="vertical"
            android:background="#e8e8e8"
            app:behavior_peekHeight="0dp"
            app:behavior_hideable="true"
            android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:layout_behavior="@string/bottom_sheet_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/floatingaction"
            android:onClick="designClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:elevation="3dp"
            app:rippleColor="@color/colorAccent"
            app:layout_anchor="@id/bottom_sheet"
            app:layout_anchorGravity="right|top"
            app:borderWidth="0dp"
            android:backgroundTint="@color/colorPrimary"
            app:pressedTranslationZ="6dp"
            android:layout_margin="10dp"
            android:src="@mipmap/ic_launcher"
            />

    </android.support.design.widget.CoordinatorLayout>
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.     CoordinatorLayout coordinatorLayout;  
  4.     RecyclerView  recyclerview;  
  5.     RecyclerView.Adapter<MyViewHolder>adapter;  
  6.     List<String>texts;  
  7.     BottomSheetBehavior<View> behavior;  
  8.   
  9.   
  10.   
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.         coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);  
  16.         recyclerview = (RecyclerView) findViewById(R.id.recyclerview);  
  17.         texts = new ArrayList<>();  
  18.         texts.add("测试1");  
  19.         texts.add("测试2");  
  20.         texts.add("测试3");  
  21.         texts.add("测试4");  
  22.         texts.add("测试5");  
  23.         texts.add("测试5");  
  24.         texts.add("测试5");  
  25.         //创建适配器  
  26.         adapter = new RecyclerView.Adapter<MyViewHolder>() {  
  27.             @Override  
  28.             public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  29.                 return new MyViewHolder(LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false));  
  30.             }  
  31.   
  32.             @Override  
  33.             public void onBindViewHolder(MyViewHolder holder, final int position) {  
  34.                 holder.getTextView(R.id.text).setText(texts.get(position));  
  35.                 holder.getTextView(R.id.text).setOnClickListener(new View.OnClickListener() {  
  36.                     @Override  
  37.                     public void onClick(View view) {  
  38.                         Toast.makeText(MainActivity.this"点击了"+position, Toast.LENGTH_SHORT).show();  
  39.                     }  
  40.                 });  
  41.   
  42.             }  
  43.   
  44.             @Override  
  45.             public int getItemCount() {  
  46.                 return texts.size();  
  47.             }  
  48.         };  
  49.         //初始化recyclerview  
  50.         recyclerview.setAdapter(adapter);  
  51.         recyclerview.setHasFixedSize(true);  
  52.         recyclerview.setItemAnimator(new DefaultItemAnimator());  
  53.         recyclerview.setLayoutManager(new LinearLayoutManager(this));  
  54.         //配置bottomSheet  
  55.         View bottomSheet =  findViewById(R.id.bottom_sheet);  
  56.         behavior = BottomSheetBehavior.from(bottomSheet);  
  57.         //设置监听bottomSheet的状态  
  58.         behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {  
  59.             @Override  
  60.             public void onStateChanged(@NonNull View bottomSheet, int newState) {  
  61.                 Log.i("tag00","新状态:"+newState);  
  62.             }  
  63.   
  64.             @Override  
  65.             public void onSlide(@NonNull View bottomSheet, float slideOffset) {  
  66.                 Log.i("tag00","拖动操作:"+slideOffset);  
  67.             }  
  68.         });  
  69.     }  
  70.   
  71.     //所有点击事件  
  72.     public void designClick(View view){  
  73.         switch (view.getId()){  
  74.             case R.id.tabLayout:  
  75.                 startActivity(new Intent(this,TabLayoutActivity.class));  
  76.                 break;  
  77.             case R.id.navigation:  
  78.                 startActivity(new Intent(this,NavigationActivity.class));  
  79.                 break;  
  80.             case R.id.collasping:  
  81.                 startActivity(new Intent(this,CollaspingActivity.class));  
  82.                 break;  
  83.             case R.id.floatingaction:  
  84.                 Snackbar.make(coordinatorLayout,"点击了floatingActionButton",Snackbar.LENGTH_LONG).show();  
  85.                 break;  
  86.             //点击BottomSheet使用,改变状态  
  87.             case R.id.design_bottom_sheet:  
  88.                 int state = behavior.getState();  
  89.                 if (state == BottomSheetBehavior.STATE_EXPANDED) {  
  90.                     behavior.setState(BottomSheetBehavior.STATE_HIDDEN);  
  91.                 }else{  
  92.                     behavior.setState(BottomSheetBehavior.STATE_EXPANDED);  
  93.                 }  
  94.                 break;  
  95.         }  
  96.     }  
  97.   
  98.     //用于展示弹窗的list  
  99.     public class MyViewHolder extends RecyclerView.ViewHolder{  
  100.        private SparseArray<View> array;  
  101.   
  102.         public MyViewHolder(View itemView) {  
  103.             super(itemView);  
  104.             array = new SparseArray<>();  
  105.         }  
  106.   
  107.         private <T extends View> T findViewById(int viewId){  
  108.             View view = array.get(viewId);  
  109.             if (view == null){  
  110.                 view = itemView.findViewById(viewId);  
  111.                 array.put(viewId,view);  
  112.             }  
  113.             return (T) view;  
  114.         }  
  115.   
  116.         private View findView(int viewId){  
  117.             return findViewById(viewId);  
  118.         }  
  119.   
  120.         public TextView getTextView(int viewid){  
  121.             return (TextView)findView(viewid);  
  122.         }  
  123.     }  
  124.   
  125. }  
public class MainActivity extends AppCompatActivity {

    CoordinatorLayout coordinatorLayout;
    RecyclerView  recyclerview;
    RecyclerView.Adapter<MyViewHolder>adapter;
    List<String>texts;
    BottomSheetBehavior<View> behavior;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        texts = new ArrayList<>();
        texts.add("测试1");
        texts.add("测试2");
        texts.add("测试3");
        texts.add("测试4");
        texts.add("测试5");
        texts.add("测试5");
        texts.add("测试5");
        //创建适配器
        adapter = new RecyclerView.Adapter<MyViewHolder>() {
            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return new MyViewHolder(LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false));
            }

            @Override
            public void onBindViewHolder(MyViewHolder holder, final int position) {
                holder.getTextView(R.id.text).setText(texts.get(position));
                holder.getTextView(R.id.text).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, "点击了"+position, Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public int getItemCount() {
                return texts.size();
            }
        };
        //初始化recyclerview
        recyclerview.setAdapter(adapter);
        recyclerview.setHasFixedSize(true);
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        //配置bottomSheet
        View bottomSheet =  findViewById(R.id.bottom_sheet);
        behavior = BottomSheetBehavior.from(bottomSheet);
        //设置监听bottomSheet的状态
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                Log.i("tag00","新状态:"+newState);
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                Log.i("tag00","拖动操作:"+slideOffset);
            }
        });
    }

    //所有点击事件
    public void designClick(View view){
        switch (view.getId()){
            case R.id.tabLayout:
                startActivity(new Intent(this,TabLayoutActivity.class));
                break;
            case R.id.navigation:
                startActivity(new Intent(this,NavigationActivity.class));
                break;
            case R.id.collasping:
                startActivity(new Intent(this,CollaspingActivity.class));
                break;
            case R.id.floatingaction:
                Snackbar.make(coordinatorLayout,"点击了floatingActionButton",Snackbar.LENGTH_LONG).show();
                break;
            //点击BottomSheet使用,改变状态
            case R.id.design_bottom_sheet:
                int state = behavior.getState();
                if (state == BottomSheetBehavior.STATE_EXPANDED) {
                    behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }else{
                    behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;
        }
    }

    //用于展示弹窗的list
    public class MyViewHolder extends RecyclerView.ViewHolder{
       private SparseArray<View> array;

        public MyViewHolder(View itemView) {
            super(itemView);
            array = new SparseArray<>();
        }

        private <T extends View> T findViewById(int viewId){
            View view = array.get(viewId);
            if (view == null){
                view = itemView.findViewById(viewId);
                array.put(viewId,view);
            }
            return (T) view;
        }

        private View findView(int viewId){
            return findViewById(viewId);
        }

        public TextView getTextView(int viewid){
            return (TextView)findView(viewid);
        }
    }

}
大致的说明都在注释里了,其实这些新控件更多的在于怎么使用,想要扣原理还是要去撸源码。看看效果吧。


最后给一个我看的比较详细的BottomSheetBehavior介绍,还介绍了它的一些扩展。感兴趣的可以去看看:

http://blog.csdn.net/qjay_dev/article/details/51289267



大致就是这么多了,还有其他未涉及的,可以去找度娘了。

参考:《Android高级进阶》

http://android-developers.blogspot.com.es/2012/05/android-design-support-library.html 谷歌官网

http://wiki.jikexueyuan.com/project/material-design/components/snackbars-and-toasts.html  极客学院

http://www.jianshu.com/p/cd1e80e64311  作者:简明

http://www.jcodecraeer.com/a/basictutorial/2015/0821/3338.html 作者:泡在网上的日子

http://blog.csdn.net/luck_apple/article/details/9207811 作者:luck_apple

http://blog.csdn.net/qjay_dev/article/details/51289267 作者:JarQ


感谢【动脑学院】老司机的赞助!


最后附上git:   https://github.com/SingleShu/MaterialDesignDemo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值