美文网首页Android-CoordinatorLayout.……
嵌套滑动机制 -- CoordinatorLayout

嵌套滑动机制 -- CoordinatorLayout

作者: TomyZhang | 来源:发表于2020-08-22 20:34 被阅读0次

    一、概念

    CoordinatorLayout 的类继承关系:

    CoordinatorLayout extends ViewGroup implements NestedScrollingParent2,
            NestedScrollingParent3
    

    主要作用:

    • 作为顶层布局;
    • 作为协调子 View 之间交互的容器。

    二、使用

    1.CoordinatorLayout 与 FloatingActionButton

    activity_main.xml:
    <?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"
        android:id="@+id/contentView"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:id="@+id/anchorView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"/>
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_anchor="@id/anchorView"
            app:layout_anchorGravity="bottom|right"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:onClick="onClick"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
    MainActivity:
    public class MainActivity extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getSimpleName();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "zwm, onCreate, Target30");
            setContentView(R.layout.activity_main);
        }
    
        public void onClick(View v) {
            Log.d(TAG, "zwm, onClick");
            switch (v.getId()) {
                case R.id.fab:
                    Snackbar.make(findViewById(R.id.contentView), "Hello, Android!", Snackbar.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    
    日志打印:
    2020-09-17 21:15:00.882 9490-9490/com.tomorrow.target30 D/MainActivity: zwm, onCreate, Target30
    2020-09-17 21:15:02.823 9490-9490/com.tomorrow.target30 D/MainActivity: zwm, onClick
    

    CoordinatorLayout 提供了两个属性用来设置 FloatingActionButton 的位置:

    • layout_anchor:设置 FloatingActionButton 的锚点。
    • layout_anchorGravity:设置 FloatingActionButton 相对锚点的位置。

    当 Snackbar 显示和隐藏的时候,CoordinatorLayout 会动态调整 FloatingActionButton 的位置。

    2.CoordinatorLayout 与 AppBarLayout

    activity_main.xml:
    <?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"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="10dp"
                android:paddingBottom="10dp"
                android:gravity="center"
                android:textSize="30sp"
                android:textColor="@android:color/white"
                android:text="Header"
                android:background="#0000FF"
                app:layout_scrollFlags="scroll"/>
        </com.google.android.material.appbar.AppBarLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
    RecyclerViewAdapter:
    public class RecyclerViewAdapter extends RecyclerView.Adapter {
        private List<RecyclerViewBean> mData;
        private LayoutInflater mInflater;
    
        public RecyclerViewAdapter(Context context, List<RecyclerViewBean> data) {
            this.mData = data;
            this.mInflater = LayoutInflater.from(context);
        }
    
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            switch (viewType) {
                case RecyclerViewBean.TYPE_ITEM:
                    return new ContentHolder(mInflater.inflate(R.layout.recyclerview_content_layout, viewGroup, false));
                case RecyclerViewBean.TYPE_TITLE:
                    return new TitleHolder(mInflater.inflate(R.layout.recyclerview_title_layout, viewGroup, false));
                default:
                    return null;
            }
        }
    
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            RecyclerViewBean infoBean = mData.get(i);
            int viewType = getItemViewType(i);
            switch (viewType) {
                case RecyclerViewBean.TYPE_ITEM:
                    ContentHolder contentHolder = (ContentHolder) viewHolder;
                    contentHolder.tvTitle.setText(infoBean.title);
                    contentHolder.tvContent.setText(infoBean.content);
                    break;
                case RecyclerViewBean.TYPE_TITLE:
                    TitleHolder titleHolder = (TitleHolder) viewHolder;
                    titleHolder.tvTitle.setText(infoBean.title);
                    break;
                default:
                    break;
            }
        }
    
        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }
    
        @Override
        public int getItemViewType(int position) {
            return mData.get(position).type;
        }
    
        public static class TitleHolder extends RecyclerView.ViewHolder {
            TextView tvTitle;
    
            TitleHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_title);
            }
        }
    
        public static class ContentHolder extends RecyclerView.ViewHolder {
            TextView tvTitle;
            TextView tvContent;
    
            ContentHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_title);
                tvContent = itemView.findViewById(R.id.tv_content);
            }
        }
    }
    
    RecyclerViewBean:
    public class RecyclerViewBean {
        public static final int TYPE_TITLE = 1;
        public static final int TYPE_ITEM = 2;
    
        public int type;
        public String title;
        public String content;
    }
    
    recyclerview_title_layout.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="#63BB0B"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:textSize="20dp"
            android:textStyle="bold"
            android:textColor="#000000"
            android:text="评论"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    recyclerview_content_layout.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        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">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:textColor="#000000"
            android:textSize="16dp"
            android:text="评论"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:textColor="#000000"
            android:textSize="16dp"
            android:text="内容"
            app:layout_constraintTop_toBottomOf="@+id/tv_title"
            app:layout_constraintLeft_toLeftOf="parent" />
        <View
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_content"
            android:layout_marginTop="5dp"
            android:layout_width="0dp"
            android:layout_height="5dp"
            android:background="#686868"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    MainActivity:
    public class MainActivity extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getSimpleName();
        private RecyclerView mRecyclerView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "zwm, onCreate, Target30");
            setContentView(R.layout.activity_main);
            initRecyclerView();
        }
    
        private void initRecyclerView() {
            mRecyclerView = findViewById(R.id.recyclerview);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            List<RecyclerViewBean> data = getCommentData();
            RecyclerViewAdapter rvAdapter = new RecyclerViewAdapter(this, data);
            mRecyclerView.setAdapter(rvAdapter);
        }
    
        private List<RecyclerViewBean> getCommentData() {
            List<RecyclerViewBean> commentList = new ArrayList<>();
            RecyclerViewBean titleBean = new RecyclerViewBean();
            titleBean.type = RecyclerViewBean.TYPE_TITLE;
            titleBean.title = "评论列表";
            commentList.add(titleBean);
            for (int i = 0; i < 40; i++) {
                RecyclerViewBean contentBean = new RecyclerViewBean();
                contentBean.type = RecyclerViewBean.TYPE_ITEM;
                contentBean.title = "评论标题" + i;
                contentBean.content = "评论内容" + i;
                commentList.add(contentBean);
            }
            return commentList;
        }
    }
    
    • CoordinatorLayout 中可滚动的 View(如上例中 RecyclerView),需要设置以下属性:

      app:layout_behavior="@string/appbar_scrolling_view_behavior"
      
    • AppBarLayout 中的 View(如上例中 TextView),如要想要滚动到屏幕外,必须设置以下属性:

      app:layout_scrollFlags="scroll"
      

      scroll 的效果为:隐藏的时候,先整体向上滚动,直到 AppBarLayout 完全隐藏,再开始滚动 Scrolling View;显示的时候,直到 Scrolling View 顶部完全出现后,再开始滚动 AppBarLayout 到完全显示。

    除了 scroll,还有下面几个取值,这些属性都必须与 scroll 一起使用 "|" 运算符:

    • enterAlways:与 scroll 类似(scroll|enterAlways),只不过向下滚动先让 AppBarLayout 完全显示,再滚动 Scrolling View:

      activity_main.xml:
      <?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"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
          <com.google.android.material.appbar.AppBarLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:paddingTop="10dp"
                  android:paddingBottom="10dp"
                  android:gravity="center"
                  android:textSize="30sp"
                  android:textColor="@android:color/white"
                  android:text="Header"
                  android:background="#0000FF"
                  app:layout_scrollFlags="scroll|enterAlways"/>
          </com.google.android.material.appbar.AppBarLayout>
          <androidx.recyclerview.widget.RecyclerView
              android:id="@+id/recyclerview"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
      </androidx.coordinatorlayout.widget.CoordinatorLayout>
      
    • enterAlwaysCollapsed:需要和 enterAlways 一起使用(scroll|enterAlways|enterAlwaysCollapsed),和 enterAlways 不一样的是,不会在 AppBarLayout 完全显示后才滚动 Scrolling View,而是先滚动 AppBarLayout 到最小高度,然后滚动 Scrolling View 直到顶部完全出现,最后再滚动 AppBarLayout 到完全显示。注意:需要定义 View 的最小高度(minHeight)才有效果:

      activity_main.xml:
      <?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"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
          <com.google.android.material.appbar.AppBarLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:paddingTop="10dp"
                  android:paddingBottom="10dp"
                  android:gravity="center"
                  android:textSize="30sp"
                  android:textColor="@android:color/white"
                  android:text="Header"
                  android:background="#0000FF"
                  android:minHeight="20dp"
                  app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"/>
          </com.google.android.material.appbar.AppBarLayout>
          <androidx.recyclerview.widget.RecyclerView
              android:id="@+id/recyclerview"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
      </androidx.coordinatorlayout.widget.CoordinatorLayout>
      
    • exitUntilCollapsed:定义了 AppBarLayout 消失的规则。发生向上滚动事件时,AppBarLayout 向上滚动退出直至最小高度(minHeight),然后 Scrolling View 开始滚动。也就是 AppBarLayout 不会完全退出屏幕:

      activity_main.xml:
      <?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"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
          <com.google.android.material.appbar.AppBarLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:paddingTop="10dp"
                  android:paddingBottom="10dp"
                  android:gravity="center"
                  android:textSize="30sp"
                  android:textColor="@android:color/white"
                  android:text="Header"
                  android:background="#0000FF"
                  android:minHeight="20dp"
                  app:layout_scrollFlags="scroll|exitUntilCollapsed"/>
          </com.google.android.material.appbar.AppBarLayout>
          <androidx.recyclerview.widget.RecyclerView
              android:id="@+id/recyclerview"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
      </androidx.coordinatorlayout.widget.CoordinatorLayout>
      

      enterAlwaysCollapsed 与 exitUntilCollapsed 在实际的使用中,更多的是与 CollapsingToolbarLayout 一起使用。

    3.CoordinatorLayout 与 CollapsingToolbarLayout

    CollapsingToolbarLayout 继承自 FrameLayout,它是用来实现 Toolbar 的折叠效果,一般它的直接子 View 是 Toolbar,当然也可以是其它类型的 View:

    activity_main.xml:
    <?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"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="150dp">
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="#0000FF"
                app:layout_scrollFlags="scroll|enterAlways">
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    app:layout_collapseMode="pin"
                    app:navigationIcon="@mipmap/ic_launcher_round"
                    app:title="Hello, Android!"/>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
    • app:contentScrim:表示 CollapsingToolbarLayout 折叠之后的“前景色”,我们看到 Toolbar 的变色,其实是因为前景色遮挡了而已。
    • app:layout_scrollFlags="scroll|enterAlways" 效果为:向下滚动先让 AppBarLayout 完全显示,再滚动 Scrolling View。
    • app:layout_collapseMode="pin" 确保 CollapsingToolbarLayout 折叠完成之前,Toolbar 一直固定在顶部不动。

    使用 app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed" 及 app:layout_collapseMode="pin",让 Toolbar 一直固定在顶部不动:

    activity_main.xml:
    <?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"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="150dp">
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="#0000FF"
                app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed">
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    app:layout_collapseMode="pin"
                    app:title="Hello, Android!"
                    app:navigationIcon="@mipmap/ic_launcher"/>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    使用 app:layout_collapseMode="parallax"、app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed" 及 app:layout_collapseMode="pin",产生视差效果:

    <?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"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="150dp">
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="#0000FF"
                app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed">
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/image"
                    android:scaleType="centerCrop"
                    app:layout_collapseParallaxMultiplier="0.9"
                    app:layout_collapseMode="parallax"/>
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    app:layout_collapseMode="pin"
                    app:title="Hello, Android!"
                    app:navigationIcon="@mipmap/ic_launcher"/>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    三、原理

    CoordinatorLayout 的核心是 Behavior,Behavior 提供了二十多个空方法给使用者来重写,主要分为四类:

    • 与 Touch 事件相关的方法
    • 与 NestedScroll 相关的方法
    • 与控件依赖相关的方法
    • 其他方法,如测量和布局等

    重要概念:

    • child,是一个 View,是该 Behavior 所要操作的对象
    • dependency,也是一个 View,是 child 的依赖对象,也是该 Behavior 对 child 进行操作的根据

    重要方法:

    • layoutDependsOn

      public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull V child,
                      @NonNull View dependency)
      

      它会被 Behavior 的 LayoutParams 的 dependsOn 方法调用:

      boolean dependsOn(CoordinatorLayout parent, View child, View dependency) {
        return dependency == mAnchorDirectChild
                || shouldDodge(dependency, ViewCompat.getLayoutDirection(parent))
                || (mBehavior != null && mBehavior.layoutDependsOn(parent, child, dependency));
      }
      

      dependsOn 方法就是用来确定依赖关系的。最简单的确定依赖关系的方法是重写 layoutDependsOn 方法,并在一定条件下返回 true 即可。

    • onDependentViewChanged

      public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull View dependency)
      

      当 dependency 发生改变的时候,这个方法会调用。

    自定义简单的 Behavior:

    activity_main.xml:
    <?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"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:background="#0000FF"
            android:textAllCaps="false"
            android:textColor="#FFFFFF"
            android:text="child"
            app:layout_behavior="com.tomorrow.target30.MyBehavior" />
        <com.tomorrow.target30.TempView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:background="#CC88CC"
            android:gravity="center"
            android:textColor="#FFFFFF"
            android:text="dependency"
            android:clickable="true"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
    MyBehavior:
    public class MyBehavior extends CoordinatorLayout.Behavior<Button> {
        private static final String TAG = MyBehavior.class.getSimpleName();
        private int mWidth;
    
        public MyBehavior(Context context, AttributeSet attrs) {
            super(context, attrs);
            DisplayMetrics display = context.getResources().getDisplayMetrics();
            mWidth = display.widthPixels;
        }
    
        @Override
        public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
            Log.d(TAG, "zwm, layoutDependsOn, parent: " + parent + ", child: " + child + ", dependency: " + dependency);
            //如果dependency是TempView的实例,说明它就是我们所需要的Dependency
            return dependency instanceof TempView;
        }
    
        //每次dependency位置发生变化,都会执行onDependentViewChanged方法
        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, Button btn, View dependency) {
            Log.d(TAG, "zwm, onDependentViewChanged, parent: " + parent + ", btn: " + btn + ", dependency: " + dependency);
            //根据dependency的位置,设置Button的位置
            int top = dependency.getTop();
            int left = dependency.getLeft();
            int x = mWidth - left - btn.getWidth();
            int y = top;
            setPosition(btn, x, y);
            return true;
        }
    
        private void setPosition(View v, int x, int y) {
            CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) v.getLayoutParams();
            layoutParams.leftMargin = x;
            layoutParams.topMargin = y;
            v.setLayoutParams(layoutParams);
        }
    }
    
    TempView:
    public class TempView extends TextView {
        private static final String TAG = TempView.class.getSimpleName();
        private int mTouchStartX;
        private int mTouchStartY;
    
        public TempView(Context context) {
            super(context);
        }
    
        public TempView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            Log.d(TAG, "zwm, onTouchEvent action: " + event.getAction());
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTouchStartX = (int) event.getX();
                    mTouchStartY = (int) event.getY();
                    Log.d(TAG, "zwm, mTouchStartX: " + mTouchStartX + ", mTouchStartY: " + mTouchStartY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    int dx = (int) event.getX() - mTouchStartX;
                    int dy = (int) event.getY() - mTouchStartY;
                    Log.d(TAG, "zwm, dx: " + dx + ", dy: " + dy);
                    setPosition(dx, dy);
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return super.onTouchEvent(event);
        }
    
        private void setPosition(int dx, int dy) {
            CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) getLayoutParams();
            layoutParams.leftMargin += dx;
            layoutParams.topMargin += dy;
            setLayoutParams(layoutParams);
        }
    }
    
    MainActivity:
    public class MainActivity extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getSimpleName();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "zwm, onCreate, Target30");
            setContentView(R.layout.activity_main);
        }
    }
    
    日志打印:
    2020-09-21 12:14:29.337 32265-32265/com.tomorrow.target30 D/MainActivity: zwm, onCreate, Target30
    2020-09-21 12:14:29.379 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......I. 0,0-0,0}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ......ID 0,0-0,0 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ......ID 0,0-0,0}
    2020-09-21 12:14:29.397 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......I. 0,0-0,0}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ......ID 0,0-0,0 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ......ID 0,0-0,0}
    2020-09-21 12:14:29.398 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......ID 0,0-1080,2232}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ......ID 0,0-264,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ......ID 0,0-226,150}
    2020-09-21 12:14:29.398 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, onDependentViewChanged, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......ID 0,0-1080,2232}, btn: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ......ID 0,0-264,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ......ID 0,0-226,150}
    2020-09-21 12:14:29.408 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ........ 0,0-1080,2232}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ........ 0,0-264,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ........ 0,0-226,150}
    2020-09-21 12:14:33.048 32265-32265/com.tomorrow.target30 D/TempView: zwm, onTouchEvent action: 0
    2020-09-21 12:14:33.048 32265-32265/com.tomorrow.target30 D/TempView: zwm, mTouchStartX: 160, mTouchStartY: 126
    2020-09-21 12:14:33.093 32265-32265/com.tomorrow.target30 D/TempView: zwm, onTouchEvent action: 2
    2020-09-21 12:14:33.093 32265-32265/com.tomorrow.target30 D/TempView: zwm, dx: 1, dy: 0
    2020-09-21 12:14:33.095 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......I. 0,0-1080,2232}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ........ 816,0-1080,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ...p..I. 0,0-226,150}
    2020-09-21 12:14:33.097 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, layoutDependsOn, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......ID 0,0-1080,2232}, child: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ........ 816,0-1080,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ...p..ID 1,0-227,150}
    2020-09-21 12:14:33.097 32265-32265/com.tomorrow.target30 D/MyBehavior: zwm, onDependentViewChanged, parent: androidx.coordinatorlayout.widget.CoordinatorLayout{88636b V.E...... ......ID 0,0-1080,2232}, btn: androidx.appcompat.widget.AppCompatButton{7dd18ba VFED..C.. ........ 816,0-1080,150 #7f080057 app:id/btn}, dependency: com.tomorrow.target30.TempView{81f1ec8 VFED..C.. ...p..ID 1,0-227,150}
    

    相关文章

      网友评论

        本文标题:嵌套滑动机制 -- CoordinatorLayout

        本文链接:https://www.haomeiwen.com/subject/vjqbjktx.html