概念分析
CoordinatorLayout 是一种协调布局,一般与 AppBarLayout 搭配着使用。
效果展示
代码展示
<?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="wrap_content">
<View
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#f00"
android:minHeight="25dp"
app:layout_scrollFlags="scroll"/>
<View
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#0f0"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_my_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
要点剖析
- CoordinatorLayout 作为根布局
- AppBarLayout 包括子布局 其中子布局可以添加 app:layout_scrollFlags="" 属性来控制动画,属性值有如下五种,大家自行尝试
scroll
scroll|enterAlways
scroll|enterAlways|enterAlwaysCollapsed //与android:minHeight="25dp"搭配使用
scroll|exitUntilCollapsed //与android:minHeight="25dp"搭配使用
scroll|snap //要么开,要么关
- 结合 RecyclerView 使用;ListView不行
- app:layout_behavior="@string/appbar_scrolling_view_behavior"这个属性不能掉,这是系统自带的 behavior,后期我会教大家写 behavior。CoordinatorLayout原理的简析
RecyclerView的写法
package com.wust.selfcoordinatorlayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private RecyclerView rv_my_test;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv_my_test = findViewById(R.id.rv_my_test);
mAdapter = new MyAdapter();
RecyclerView.LayoutManager lm = new LinearLayoutManager(this);
rv_my_test.setLayoutManager(lm);
rv_my_test.setAdapter(mAdapter);
}
private class MyAdapter extends RecyclerView.Adapter{
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
TextView tv = new TextView(MainActivity.this);
return new MyVh(tv);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
MyVh ho = (MyVh) holder;
TextView tv = (TextView) ho.itemView;
tv.setText("position ->" + position);
}
@Override
public int getItemCount() {
return 100;
}
private class MyVh extends RecyclerView.ViewHolder{
public MyVh(@NonNull View itemView) {
super(itemView);
}
}
}
}