Recycler 与 CoordinatorLayout配合使用
在我们的日常工作中,用到折叠布局的时候一般都是配合RecyclerView使用,或者直接使用Scroll控件,这篇文章就是简单的实现折叠布局,完全解析请移步:CoordinatorLayout 完全解析 本文章也是参考此文章。
引入依赖
理论上是不需要引入任何依赖的因为Google会自带,不过还是在这里贴一条,CoordinatorLayout是AndroidX里面的Material包内的,引入方法为添加下列依赖
implementation 'com.google.android.material:material:1.3.0'
编写布局
先把完整的布局代码展示出来,至于RecyclerView的Item 和Adapter在这里就不做赘述了,就是一个很简单的列表和一个TextView的Item
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="250dp">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#00ff00"
app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed"
android:id="@+id/collapsing">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/bg"/>
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
app:layout_collapseMode="pin"
android:minHeight="10dp"
app:logo="@mipmap/ic_launcher"
app:title="标题"
android:layout_height="60dp"/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recycler"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
布局解析:
- 首先是根布局要使用CoordinatorLayout,当然 如果您想使用下拉刷新等可以在外面包布局,这里就不考虑了。
- 要注意的一点是,在AppBarLayout里面的布局可以替换,这里是因为有很多特效,动画所以使用了bar组件。
- 关键的一点是要在顶部布局添加
app:layout_scrollFlags
使得布局作为头部与CoordinatorLayout交互,其次就是所指的属性可以参考本文章前面的参考文章,这里面讲的很详细。 - 之后在CoordinatorLayout里面套入RecycleView即可,我们不需要做任何操作,如果出现item被挡住的问题,可以在
CollapsingToolbarLayout
添加android:minHeight="?actionBarSize"
非常简单的一个联动 至于java代码 在这里也贴一下吧
RecyclerView recyclerView;
List<String> mList =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i =0;i<100;i++){
mList.add(i+"--");
}
recyclerView = findViewById(R.id.recycler);
RecyclerviewAdapter recyclerviewAdapter =new RecyclerviewAdapter(this,mList);
recyclerView.setAdapter(recyclerviewAdapter);
}