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