看了郭霖第一行代码第二版这本书,第12章讲的材料设计,动手练习记录如下。
1、ToolBar替换ActionBar
将styles.xml文件的parent指定为“Theme.AppCompat.Light.NoActionBar”。因为该styles.xml文件被AndroidManifest.xml文件的application节点的 android:theme=”@style/AppTheme”所引用。
<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>
修改activity_main.xml布局文件,app:popupTheme属性单独将弹出的菜单项指定成淡色主题,避免和ToolBar的淡色风格不一致。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
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"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</RelativeLayout>
在MainActivity的onCreate方法中加入如下代码:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
经过以上处理后,就可以实现ToolBar替换ActionBar
2、在ToolBar上加入action按钮。
在menu文件夹下创建一个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/ic_backup"
android:title="Backup"
app:showAsAction="always" />
<item
android:id="@+id/delete"
android:icon="@drawable/ic_delete"
android:title="Delete"
app:showAsAction="ifRoom" />
<item
android:id="@+id/settings"
android:icon="@drawable/ic_settings"
android:title="Settings"
app:showAsAction="never" />
</menu>
app:showAsAction属性有以下可选值:always表示永远显示在Toolbar中(如果屏幕空间不够则不显示);ifRoom表示屏幕空间足够的情况下显示在Toolbar中,不够的话显示在菜单中;never表示永远显示在菜单中。
在MainActivity中加入菜单的回调方法
@Override
public boolean onCreateOptionsMenu(Menu menu) {
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 clicked Backup", Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this, "You clicked Delete", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this, "You clicked Settings", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
3、滑动菜单(DrawerLayout)
首先它是一个布局,在布局中允许放入两个直接子控件,第一个控件是主屏幕中显示的内容,第二个子控件是滑动菜单中显示的内容。修改activity_main.xml后如下:
<?xml version="1.0" encoding="utf-8"?>
<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:background="@android:color/white"
android:text="这是菜单"
android:textSize="30sp" />
</android.support.v4.widget.DrawerLayout>
这里最外层的控件换成了DrawerLayout,第一个子控件是FrameLayout,用于在主屏幕中显示。第二个子控件使用了一个TextView,用于在滑动菜单中显示。其实DrawerLayout并没有限制只能使用固定的控件。
特别强调的是,第二个子控件的android:layout_gravity=”start”属性必须要设置,用来告诉DrawerLayout在屏幕的左边还是右边显示。“start”表示会根据系统语言进行判断,如果系统语言是从左到右的,比句汉语、英语,菜单就在左侧显示。阿拉伯语跟我们的正好相反。
4、在ToolBar的最左侧加入导航按钮
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
...
}
return true;
}
}
通过调用getSupportActionBar()方法得到ActionBar实例,接着调用ActionBar的setDisplayHomeAsUpEnabled()方法来设置一个导航按钮图标。其实Toolbar最左侧的这个按钮叫做HomeAsUp按钮,它默认的图标是一个返回箭头,含义是返回上一个活动。很明显,这里我们将它的默认样式和作用都进行了修改。接下来在onOptionsItemSelected()方法中对HomeAsUp按钮的点击事件进行处理,该按钮的id永远都是android.R.id.home,然后调用DrawerLayout的openDrawer()方法将滑动菜单展示出来。
5、NavigationView(在滑动菜单里定制布局)
在app/build.gradle文件的dependencies闭包中加入依赖,
compile ‘com.android.support:design:25.0.1’
compile ‘de.hdodenhof:circleimageview:2.1.0’
第一个依赖是Design Support库,第二个依赖是个开源项目,用来给图片圆形化。
在使用NavigationView之前,先准备两个文件menu和headerLayout。
menu用来显示具体的菜单项,headerLayout用来在NavigationView中显示头部布局。
在menu文件夹下加入nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<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>
在group标签表示一个组,android:checkableBehavior=”single”表示所有菜单项只能单选。
在layout文件夹下加入nav_header.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="?attr/colorPrimary"
android:padding="10dp">
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="tonygreendev@gmail.com"
android:textColor="#FFF"
android:textSize="14sp" />
<TextView
android:id="@+id/mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/username"
android:text="Tony Green"
android:textColor="#FFF"
android:textSize="14sp" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/icon_image"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="@drawable/nav_icon"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
修改activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<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.NavigationView
android:id="@+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
将之前的TextView替换成NavigationView,这样滑动菜单中显示的内容也就变成了NavigationView了。这里通过app:headerLayout和app:menu属性将刚才准备的nav_header和nav_menu布局设置进去即可。
修改MainActivity的代码:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
navView.setCheckedItem(R.id.nav_call);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
mDrawerLayout.closeDrawers();
return true;
}
});
}
...
}
navView.setCheckedItem(R.id.nav_call)将Call菜单项设置为默认选中。setNavigationItemSelectedListener()方法来设置一个菜单项选中事件的监听器。这里只是简单的关闭滑动菜单closeDrawers()。
6、悬浮按钮和可交互提示
修改activity_main.xml,在FrameLayout里加入FloatingActionButton即可。so easy~~~
<?xml version="1.0" encoding="utf-8"?>
<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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_done" />
</FrameLayout>
...
</android.support.v4.widget.DrawerLayout>
在MainActivity中加入点击事件,和普通Button一样
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "哥是悬浮按钮", Toast.LENGTH_SHORT).show();
}
});
7、Snackbar(用来提示)
Snackbar并不 Toast的替代品,它们两者之间有不同的使用场景。Toast的作用是告诉用户现在发生了什么事,但用户只能被动接收,没有办法让用户选择。Snackbar允许在提示中加入一个可交互按钮,它允许在提示中加入一个可交互按钮,当用户点击按钮的时候可以执行一些额外的逻辑操作。
修改MainActivity的代码
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "是否删除", Snackbar.LENGTH_INDEFINITE)
.setAction("撤销", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "数据已恢复", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
make()方法用来创建一个Snackbar对象,该方法的第一个参数需要传入一个View,只要是当前界面布局的任意一个View都可以,Snackbar会使用这个View来自动查找最外层的布局,用于展示Snackbar。setAction()方法用来设置一个动作,从而让Snackbar不仅仅是一个提示,还可以和用户进行交互。
发现一个问题,Snackbar把悬浮按钮遮挡住了,可以借助CoordinatorLayout就可以解决。
8、CoordinatorLayout
CoordinatorLayout可以说是一个加强版的FrameLayout,可以监听所有子控件的各种事件,然后自动帮助我们做出最合理的响应。
刚才弹出的Snackbar提示将悬浮按钮遮挡住了,如果我们能让CoordinatorLayout监听到Snackbar的弹出事件,那么它就会自动将内部的FloatingActionButton向上偏移,从而不会被Snackbar遮挡住。
我们只需将原来的FrameLayout替换成CoordinatorLayout即可。
原因:之前在Snackbar的make()方法传入的第一个参数,这个参数就是用来指定Snackbar是用来指定哪个View来触发的,刚才我们传入的是FloatingActionButton本身,而现在经过布局修改后,FloatingActionButton是CoordinatorLayout 中的子控件,因此这个事件就可以被监听到了。
<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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
9、CardView
CardView用来实现卡片式布局效果的重要控件,由appcompat-v提供。实际上CardView也是FrameLayout,只是额外提供了圆角和阴影效果。
在app/build.gradle加入依赖
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
修改activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
...
</android.support.v4.widget.DrawerLayout>
这里在CoordinatorLayout中加入了RecyclerView
接着定义一个实体类Fruit
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
接着需要给RecyclerView的子项指定一个自定义布局fruit_item.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<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作为子项的最外层布局。由于CardView是一个FrameLayout,因此它没有什么方便的定位方式,所以嵌套一个LinearLayout。
接下来为Recycler准备一个适配器,FruitAdapter,继承自RecyclerView.Adapter,并将泛型指定为FruitAdapter.ViewHolder
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private Context mContext;
private List<Fruit> mFruitList;
public FruitAdapter(List<Fruit> mFruitList) {
this.mFruitList = mFruitList;
}
static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView fruitImage;
private TextView fruitName;
public ViewHolder(View view) {
super(view);
cardView = (CardView) view;
fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
fruitName = (TextView) view.findViewById(R.id.fruit_name);
}
}
@Override
public ViewHolder onCreateViewHolder(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());
Glide.with(mContext).load(fruit.getImageId()).into(holder.fruitImage);
}
@Override
public int getItemCount() {
return mFruitList.size();
}
}
这里唯一需要注意的是在onBindViewHolder()方法中使用了Glide加载图片
修改MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private Fruit[] fruits = {new Fruit("Apple", R.drawable.apple), new Fruit("Banana", R.drawable.banana),
new Fruit("Orange", R.drawable.orange), new Fruit("Watermelon", R.drawable.watermelon),
new Fruit("Pear", R.drawable.pear), new Fruit("Grape", R.drawable.grape),
new Fruit("Pineapple", R.drawable.pineapple), new Fruit("Strawberry", R.drawable.strawberry),
new Fruit("Cherry", R.drawable.cherry), new Fruit("Mango", R.drawable.mango)};
private List<Fruit> fruitList = new ArrayList<>();
private FruitAdapter adapter;
private void initFruits() {
fruitList.clear();
for (int i = 0; i < 50; i++) {
Random random = new Random();
int index = random.nextInt(fruits.length);
fruitList.add(fruits[index]);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
initFruits();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
GridLayoutManager layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
}
}
运行后效果如下:
发现一个问题,Toolbar被RecyclerView遮挡住。
10、AppBarLayout
AppBarLayout实际上是一个垂直方向的LinearLayout,它的内部做了很多滚动事件的封装,并应用了一些Material Design的设计理念。
接下来分析一下为什么RecyclerView会把Toolbar遮挡住!由于RecyclerView和Toolbar都是放置在CoordinatorLayout中的,CoordinatorLayout又是FrameLayout的加强版,那么FrameLayout中的所有控件在不进行明确定位的情况下,默认都会摆放在布局的左上角,所以产生遮挡的想象。
通过AppBarLayout只需两步就可以搞定刚才遮挡的问题!
第一步将Toolbar嵌套到AppBarLayout中;第二步给RecyclerView指定一个布局行为。
修改activity_main.xml
<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" />
</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滚动的时候就已经将滚动事件通知给了AppBarLayout,当AppBarLayout接收到滚动事件的时候,它内部的子控件(Toolbar)其实是可以指定如何去影响这些事件的。通过app:layout_scrollFlags属性就可以实现。
修改activity_main.xml文件
<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:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
...
</android.support.design.widget.CoordinatorLayout>
这里在Toolbar上添加了一个app:layout_scrollFlags属性,其中scroll表示当RecyclerView向上滚动时,Toolbar会跟着一起向上滚动并隐藏;enterAlways表示当RecyclerView向下滚动时,Toolbar会跟着一起向下滚动并重新显示;snap表示当Toolbar还没有完全隐藏或显示的时候,会根据当前滚动距离,自动选择隐藏还是显示。
11、下拉刷新(SwipeRefreshLayout)
SwipeRefreshLayout由support-v4库提供,把想要实现下拉刷新的控件放到SwipeRefreshLayout中就可以让这个控件支持下拉刷新。
<?xml version="1.0" encoding="utf-8"?>
<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: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>
可以看到,在RecyclerView的外面嵌套了一层SwipeRefreshLayout,这样RecyclerView就可以下拉刷新了。另外注意:由于RecyclerView现在变成了SwipeRefreshLayout的子控件,因此之前的app:layout_behavior声明布局行为现在要转移到SwipeRefreshLayout中。
不过还没结束,虽然RecyclerView已经支持下拉刷新功能, 还要在代码中处理逻辑才行。
public class MainActivity extends AppCompatActivity {
...
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshFruits();
}
});
}
private void refreshFruits() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
initFruits();
adapter.notifyDataSetChanged();
//表示刷新事件结束,并隐藏刷新进度条
swipeRefreshLayout.setRefreshing(false);
}
});
}
}).start();
}
12、可折叠式标题栏(CollapsingToolbarLayout)
虽说我们现在的标题栏使用Toolbar来编写的,不过它和传统的ActionBar没什么两样,只不过可以响应RecyclerView的滚动事件来进行隐藏和显示。而Material Design中并没有限定标题栏必须是酱婶的。我们现在就来实现一个可折叠式标题栏的效果,需要借助CollapsingToolbarLayout。
CollapsingToolbarLayout不能独立存在,它在设计时就被限定只能作为AppBarLayout的直接子布局来使用。而AppBarLayout又必须是CoordinatorLayout的子布局。
下面以水果详情页作为示例来说明
activity_fruit.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<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"
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.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="wrap_content"
android:orientation="vertical">
<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="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
</android.support.v7.widget.CardView>
</LinearLayout>
</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/ic_comment"
app:layout_anchor="@id/appBar"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
CollapsingToolbarLayout的 app:contentScrim 属性用于指定CollapsingToolbarLayout在趋于折叠状态以及折叠之后的背景色,其实CollapsingToolbarLayout在折叠之后就是一个普通的Toolbar,那么背景色应该是colorPrimary。app:layout_scrollFlags属性的scroll表示CollapsingToolbarLayout会随着水果内容详情的滚动一起滚动,exitUntilCollapsed表示当CollapsingToolbarLayout随着滚动完成折叠之后就保留在界面上,不再移出屏幕。
CollapsingToolbarLayout中定义的ImageView和Toolbar,app:layout_collapseMode=”parallax” 用于指定当前控件在CollapsingToolbarLayout折叠过程中的折叠模式,ImageView指定成“parallax”,表示会在折叠过程中产生一定的错位偏移,这种模式视觉效果好、Toolbar指定成pin,表示在折叠过程中位置始终保持不变。
NestedScrollView在ScrollView基础上增加了嵌套响应滚动事件的功能。最后加入了一个悬浮按钮FloatingActionButton,app:layout_anchor=”@id/appBar”指定一个锚点。
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 = getIntent();
String fruitName = intent.getStringExtra(FRUIT_NAME);
int fruitImageId = intent.getIntExtra(FRUIT_IMAGE_ID, 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
CollapsingToolbarLayout collapsingToolbar = (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);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
collapsingToolbar.setTitle(fruitName);
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();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
FruitAdapter中的点击事件处理
@Override
public ViewHolder onCreateViewHolder(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);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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;
}
13、充分利用系统状态栏空间
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="250dp"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
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:fitsSystemWindows="true"
android:scaleType="centerCrop"
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.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
...
</android.support.design.widget.CoordinatorLayout>
在CoordinatorLayout、AppBarLayout、CollapsingToolbarLayout、ImageView分别加入android:fitsSystemWindows=”true”属性。还必须在主题中将状态栏颜色指定为透明色,android:statusBarColor属性在API21(Android5.0)才有的,所以在res目录下创建values-21目录,新建styles.xml文件
加入:
<style name="FruitActivityTheme" parent="AppTheme">
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
同时还为了低版本,在values目录的styles.xml文件中加入:
<style name="FruitActivityTheme" parent="AppTheme">
</style>
最后,在AndroidManifest.xml文件中,让FruitActivity使用这个主题
<activity
android:name=".FruitActivity"
android:theme="@style/FruitActivityTheme"/>