它是由谷歌设计师基于传统优秀的设计原则,结合丰富的创意和科学技术所发明的一套全新的界面设计语言,包括了视觉、运动、互动效果等特性。
一、Toolbar
(一)创建Toolbar
Material控件中的一个控件,类似于ActionBar。
1、将res/values/styles.xml文件中的parent属性改为Theme.AppCompat.Light.NoActionBar。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="FruitActivityTheme" parent="AppTheme">
</style>
</resources>
2、修改activity_main中代码,将Toolbar放在一个FrameLayout内。
<FrameLayout
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">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</FrameLayou>
Toolbar高度设置为ActionBar的高度,android:theme属性为Toolbar的主题,app:popupThem属性单独将弹出的菜单项指定为淡色主题。
3、修改MainActivity中代码。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到Toolbar实例
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); //使用Toolbar同时使其外观与功能与ActionBar一致
}
}
(二)修改标题栏显示文字的内容
1、修改AndroidManifest中< activity>的label属性。
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="Fruits">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
(三)在Toolbar中添加action按钮
1、准备几张图片作为按钮的图标,放在drawable目录下。
2、右击res目录→New→Directory,创建一个menu文件夹。然后右击menu文件夹→New→Menu resource file,创建一个toolbar.xml文件。
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/backup"
android:icon="@drawable/backup"
android:title="Backup"
app:showAsAction="always"/>
<item
android:id="@+id/delete"
android:icon="@drawable/delete"
android:title="Delete"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/settings"
android:icon="@drawable/settings"
android:title="Settings"
app:showAsAction="never"/>
</menu>
其中通过<item>标签定位action按钮,app:showAsAction属性指定按钮显示的位置。
always表示永远显示在Toolbar中,如果屏幕空间不够这不显示。
ifRoom表示屏幕空间足够的情况下显示则Toolbar中,不够的话显示在菜单中。
never则表示永远显示在菜单中。
3、修改MainActivity中代码。
public class MainActivity extends AppCompatActivity {
……
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//加载toolbar.xml文件
getMenuInflater().inflate(R.menu.toolbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//处理点击事件
switch (item.getItemId()){
case R.id.backup:
Toast.makeText(this, "You Click Backup", Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this, "You Click Delete", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this, "You Click Settings", Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
}
二、滑动菜单
滑动菜单是将一些菜单选项隐藏起来,而不是放置在主屏幕中,然后通过滑动的方式将菜单显示出来。
(一)DrawerLayout
DrawerLayout控件是一个布局,它允许放入两个直接子控件,第一个子控件为主屏幕中显示的内容。第二个子控件为滑动菜单中显示的内容。
1、修改activity_main中代码,使DrawerLayout嵌套FrameLayou和TextView两个子控件。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</ FrameLayout >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:text="This is menu"
android:textSize="30sp"
android:background="#FFF"/>
</android.support.v4.widget.DrawerLayout>
其中第二个子控件android:layout_gravity属性是必须指定的,它告诉DrawerLayout滑动菜单是从屏幕左边还是右边出现,left、right、start和end选项。
2、在Toolbar的最左边加入导航按钮,点击该按钮也可将滑动菜单中的内容显示出来。
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
//让导航按钮显示出来
actionBar.setDisplayHomeAsUpEnabled(true);
//设置导航按钮图标
actionBar.setHomeAsUpIndicator(R.drawable.menu);
}
}
……
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
//HomeAsUp按钮的id永远为android.R.id.home
case android.R.id.home:
//展示滑动菜单,其中参数必须与XML文件中定义的一致
mDrawerLayout.openDrawer(GravityCompat.START);
break;
……
default:
}
return true;
}
}
(二)NavigationView
NavigationView是Material Support库中提供的一个控件,使滑动菜单页面的实现变得十分简单。
1、在app/build.gradle文件,dependencies闭包中添加依赖,其中circleimageview可以轻松实现图片圆化功能。
compile 'com.android.support:design:26.0.0-alpha1'
compile 'de.hdodenhof:circleimageview:2.1.0'
2、准备几张图片作为按钮的图标,放在drawable目录下。
3、右击menu文件夹→New→Menu resource file,创建一个nav_menu.xml文件,定义五个菜单项。
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_call"
android:icon="@drawable/nav_call"
android:title="Call" />
<item
android:id="@+id/nav_friends"
android:icon="@drawable/nav_friends"
android:title="Friends" />
<item
android:id="@+id/nav_location"
android:icon="@drawable/nav_location"
android:title="Location" />
<item
android:id="@+id/nav_mail"
android:icon="@drawable/nav_mail"
android:title="Mail" />
<item
android:id="@+id/nav_task"
android:icon="@drawable/nav_task"
android:title="Tasks" />
</group>
</menu>
<menu>标签中嵌套<group>标签,将<group>的checkableBehavior属性设为single,表示只能单选。
4、准备一张正方形图片作为头像,然后右击layout文件夹→New→Layoutresource file,创建一个nav_header.xml文件。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="180dp"
android:padding="10dp"
android:background="?attr/colorPrimary">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/icon_image"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="@drawable/nav_icon"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="liubowen9368@163.com"
android:textColor="#FFF"
android:textSize="14sp"/>
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/mail"
android:text="Liu Bowen"
android:textColor="#FFF"
android:textSize="14sp"/>
</RelativeLayout>
其中CircleImageView文图片圆化控件,另外两个TextView用于显示用户名和邮箱。
5、修改activity_main文件,将TextView替换为NavigationView。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</ FrameLayout >
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_menu"
app:headerLayout="@layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
6、修改MainActivity代码,处理菜单项点击事件。
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//获取NavigationView实例
NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
}
//设置Cal菜单项为默认选中
navView.setCheckedItem(R.id.nav_call);
//设置菜单选中事件的监听器,当用户点击菜单项时,回调onNavigationItemSelected方法。
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
mDrawerLayout.closeDrawers();
return true;
}
});
}
……
}
三、悬浮按钮FloatingActionButton
悬浮按钮不属于主界面平面的一部分,位于另外一个维度,给人以悬浮的感觉。
1、修改activity_main文件,添加FloatingActionButton。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/done"/>
</android.support.design.widget.CoordinatorLayout>
</ FrameLayout >
…..
</android.support.v4.widget.DrawerLayout>
主屏幕中加入FloatingActionButton。设置layout_gravity为bottom|end,其中end与之前的start一样如果系统语言从左到右那么end表示在右边,反正则在左边。
2、指定FloatingActionButton的高度。
android:elevation="8dp"
高度值越大,投影范围越大,但投影效果越淡,高度值越小,投影范围越小,但投影效果越浓。
3、修改MainActivity中代码。
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
……
//获取FloatingActionButton实例,设置监听。
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "FAB clicked", Toast.LENGTH_SHORT).show();
}
});
}
……
}
四、可交互提示Snacker
Snacker与Toast的区别:
Toast的作用是告诉用户现在发生了什么,同时用户只能被动接收,无法让用户进行选择。
Snacker在这方面进行了扩展,属于可交互提示,允许在提示中加入可交互按钮,当用户点击按钮时可以执行一些额外逻辑操作。
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
……
//获取FloatingActionButton实例,设置监听。
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//调用make()方法创建Snackbar对象,第一个参数传入一个当前界面布局的任何一个View,Snackbar会根据这个View自动寻找最外层布局,第二个参数是Snackbar显示的内容,第三参数是显示时长。
Snackbar.make(view, "Data deleted", Snackbar.LENGTH_SHORT)
// setAction()方法设置一个动作,使Snackbar可交互
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Data restored", Toast.LENGTH_SHORT).show();
}
}).show(); }
});
}
……
}
五、CoordinatorLayout
CoordinatorLayout是一个加强版FrameLayout,它可以监听其所有子控件的各种事件,然后自动帮助我们做出合理的相应。刚才上文弹出的Snackbar提示会将悬浮按钮遮挡住,当用CoordinatorLayout监听Snackbar的弹出事件,那么它会自动将内部的FloatingActionButton向上偏移,而保证不会被Snackbar遮挡住。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/done"/>
</android.support.design.widget.CoordinatorLayout>
……
</android.support.v4.widget.DrawerLayout>
六、卡片式布局CardView
1、在app/build.gradle文件,dependencies闭包中添加依赖。
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.github.bumptech.glide:glide:3.7.0'
Glide是一个强大的图片加载库,它可以用来加载本地图片、网络图片、GIF图片等,只需一行代码就能轻松实现复杂图片的加载功能。
2、修改activity_main文件,添加RecyclerView。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/done"/>
</android.support.design.widget.CoordinatorLayout>
……
</android.support.v4.widget.DrawerLayout>
3、定义Fruit实体类。
public class Fruit {
private String name; //水果名称
private int imageId; //水果对应图片的资源id
public Fruit( String name,int imageId) {
this.imageId = imageId;
this.name = name;
}
public int getImageId() {
return imageId;
}
public String getName() {
return name;
}
}
4、在layout目录下新建fruit_item.xml,为RecyclerView的子项指定自定位布局。
<android.support.v7.widget.CardView
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="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="4dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp"
android:textSize="16sp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
其中CardView是一个FrameLayout,所以在其中嵌套一个LinearLayout,用于放置更多的控件。app:cardCornerRadius属性用于指定卡片圆角的弧度,数值越大圆角弧度越大。android:scaleType属性用于指定图片的缩放模式,使用centerCrop让图片保持原有比例充满ImageView,并将超出部分裁减掉。
5、为RecyclerView创建适配器,新建FruitAdapter类。
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private Context mContext;
private List<Fruit> mFruitList;
static class ViewHolder extends RecyclerView.ViewHolder{
CardView cardView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View view) {
super(view);
cardView = (CardView) view;
fruitImage = view.findViewById(R.id.fruit_image);
fruitName = view.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> mFruitList) {
this.mFruitList = mFruitList;
}
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
if(mContext == null){
mContext = parent.getContext();
}
View view = LayoutInflater.from(mContext).inflate(R.layout.fruit_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Fruit fruit = mFruitList.get(position);
holder.fruitName.setText(fruit.getName());
//首先调用with()方法并传入一个Content,调用load()方法加载图片,调用into()方法将图片设置到一个具体的ImageView
Glide.with(mContext).load(fruit.getImageId()).into(holder.fruitImage);
}
@Override
public int getItemCount() {
return mFruitList.size();
}
}
6、修改MainActivity中代码。
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private Fruit[] fruits = {
new Fruit("Apple", R.drawable.apple), new Fruit("Cherry", R.drawable.cherry),
new Fruit("Banana", R.drawable.banana),new Fruit("Orange", R.drawable.orange),
new Fruit("Watermelon", R.drawable.watermelon),new Fruit("Kiwifruit", R.drawable.kiwifruit),
};
private List<Fruit> fruitList = new ArrayList<>();
private FruitAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
……
initFruit();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//设置每行中有两列数据
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
}
//随机产生Fruit实例
private void initFruit() {
fruitList.clear();
for(int i = 0; i < 50; i++){
Random random = new Random();
int index = random.nextInt(fruits.length);
fruitList.add(fruits[index]);
}
}
}
七、AppBarLayout
上文中因为RecyclerView和Toolbar都位于CoordinatorLayout中,而CoordinatorLayout就是一个加强版FrameLayout,所以位于同一个FrameLayout中的两个空间会存在遮挡问题。
AppBarLayout是一个垂直方向的LinearLayout,它在内部做了很多滚动事件的封装,并应用了一些Material Design的设计理念。
1、修改activity_main文件,将Toolbar嵌套到AppBarLayout中。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
……
</android.support.design.widget.CoordinatorLayout>
……
</android.support.v4.widget.DrawerLayout>
RecyclerView中使用 app:layout_behavior属性指定了一个布局行为。
2、当RecyclerView滚动时已经将滚动事件通知给AppBarLayout,修改activity_main文件,在Toolbar中加入app:layout_scrollFlags属性。
app:layout_scrollFlags="scroll|enterAlways|snap"
scroll表示RecyclerView向上滚动时,Toolbar会跟着一起向上滚动并隐藏。
enterAlways表示RecyclerView向下滚动时,Toolbar会跟着一起向下滚动并显示。
snap表示RecyclerView当Toolbar还没有完全隐藏或显示时,Toolbar会根据当前滚动的距离,自动选择隐藏还是显示。
八、下拉刷新
SwipeRefreshLayout是用于实现下拉刷新功能的核心类。只需把想要实现下拉刷新功能的控件放置到SwipeRefreshLayout中,就可以让该控件支持下拉刷新。
1、修改activity_main文件,将RecyclerView放入SwipeRefreshLayout内,实现下拉刷新。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
……
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
……
</android.support.design.widget.CoordinatorLayout>
……
</android.support.v4.widget.DrawerLayout>
2、修改MainActivity中代码,实现具体刷新逻辑。
public class MainActivity extends AppCompatActivity {
……
private SwipeRefreshLayout swipeRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
……
//获取SwipeRefreshLayout实例
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
//设置下拉刷新进度条颜色
swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
//下拉刷新监听,回调onRefresh()方法
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshFruits();
}
});
}
private void refreshFruits() {
new Thread(new Runnable() {
@Override
public void run() {
try {
//沉睡2s,模拟刷新
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
initFruit(); //重新生成数据
adapter.notifyDataSetChanged(); //通知adapter数据变化
swipeRefresh.setRefreshing(false); //表示刷新事件结束
}
});
}
}).start();
}
……
}
九、可折叠式标题栏
(一)CollapsingToolbarLayout
CollapsingToolbarLayout是作用域Toolbar基础之上的布局,它可以让Toolbar的效果更加丰富。但CollapsingToolbarLayout不能独立存在,它被限定只能作为AppBarLayout的子布局使用。
1、右击com.launcher.materialtest,新建一个FruitActivity,并指定布局名为activity_fruit.xml。
2、修改activity_fruit.xml中的 代码,定义水果标题栏。
<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">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="250dp">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/fruit_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
其中app:contentScrim属性用于指定CoordinatorLayout在趋于折叠状态以及折叠之后的背景色,CoordinatorLayout在折叠之后就是一个简单的Toolbar。
ImageView与TextView中,app:layout_collapseMode属性用于指定当前控件在CoordinatorLayout折叠过程中的折叠模式。pin表示在折叠过程中位置始终保持不变,parallax表示折叠过程中产生一定的错位偏移。
3、修改activity_fruit.xml中的 代码,定义水果内容详情。
<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">
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="35dp"
app:cardCornerRadius="4dp">
<TextView
android:id="@+id/fruit_content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
4、修改activity_fruit.xml中的 代码添加一个FloatingActionButton。
<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">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="250dp">
……
</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">
…….
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:src="@drawable/comment"
app:layout_anchor="@id/appBar"
app:layout_anchorGravity="bottom|end"/>
</android.support.design.widget.CoordinatorLayout>
其中app:layout_anchor属性指定了一个锚点,我们将锚点设定为AppBarLayout,这样悬浮按钮会出现在水果标题栏区域内。app:layout_anchorGravity属性将悬浮按钮定位到标题栏的右下角。
5、修改FruitActivity中代码。
public class FruitActivity extends AppCompatActivity {
public static final String FRUIT_NAME = "fruit_name";
public static final String FRUIT_IMAGE_ID = "fruit_image_id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fruit);
//获取Intent数据
Intent intent = getIntent();
String fruitName = intent.getStringExtra(FRUIT_NAME);
int fruitImageId = intent.getIntExtra(FRUIT_IMAGE_ID, 0);
//获取各控件实例
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
ImageView fruitImageView = (ImageView) findViewById(R.id.fruit_image_view);
TextView fruitContentText = (TextView) findViewById(R.id.fruit_content_text);
setSupportActionBar(toolbar);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
//启用HomeAsUp按钮
actionBar.setDisplayHomeAsUpEnabled(true);
}
//水果名设置为当前标题
collapsingToolbarLayout.setTitle(fruitName);
// Glide加载传入水果图片到ImageView
Glide.with(this).load(fruitImageId).into(fruitImageView);
String fruitContent = generateFruitContent(fruitName);
fruitContentText.setText(fruitContent);
}
private String generateFruitContent(String fruitName) {
StringBuilder fruitContent = new StringBuilder();
for(int i = 0; i < 500; i++){
fruitContent.append(fruitName);
}
return fruitContent.toString();
}
//处理HomeAsUp点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
6、处理RecyclerView点击事件,修改FruitAdapter中代码。
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
……
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
if(mContext == null){
mContext = parent.getContext();
}
View view = LayoutInflater.from(mContext).inflate(R.layout.fruit_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
//为CardView注册点击事件,启动FruitActivity
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Intent intent = new Intent(mContext, FruitActivity.class);
intent.putExtra(FruitActivity.FRUIT_NAME,fruit.getName());
intent.putExtra(FruitActivity.FRUIT_IMAGE_ID,fruit.getImageId());
mContext.startActivity(intent);
}
});
return holder;
}
……
}
(二)使背景图与状态栏融合到一起
1、在CoordinatorLayout、AppBarLayout与CollapsingToolbarLayout中加入android:fitsSystemWindows="true"属性,表示该控件会出现在系统状态栏里。
2、在程序的主题中将状态栏颜色指定为透明色,在主题中将android:statusBarColor属性指定为@android:color/transparent。右击res目录→New→Directory,创建values-v21目录,右击values-v21目录→New→Value resource file,创建一个styles.xml文件。
<resources>
<style name="FruitActivityTheme" parent="AppTheme">
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
定义一个FruitActivityTheme主题专门给FruitActivity使用,FruitActivityTheme主题parent主题为AppTheme,即它继承了AppTheme中所有的特性。
3、在values/styles.xml文件中修改,同样定义一个FruitActivityTheme主题。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="FruitActivityTheme" parent="AppTheme">
</style>
</resources>
实现系统差异型效果。
4、在AndroidManifest中使用android:theme属性单独给FruitActivity指定FruitActivityTheme主题。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.launcher.materialtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
……
<activity android:name=".FruitActivity"
android:theme="@style/FruitActivityTheme">
</activity>
</application>
</manifest>