A brief discussion on CoordinatorLayout

Directory

Article directory

  • Table of contents
    • 1.What is CoordinatorLayout
    • 2. Features of CoordinatorLayout
    • 3. Usage of CoordinatorLayout
    • 4.CoordinatorLayout related attribute methods
      • Properties of CoordinatorLayout
      • Behavior method
      • Methods of CoordinatorLayout
    • 4.Usage of CoordinatorLayout

In Android development, we often need to deal with complex interface interactions and coordination operations. CoordinatorLayout is a useful layout container from the Android Support library that provides flexible and powerful functionality for managing interaction and coordination between subviews. This article will explore the features, usage, and some common application scenarios of CoordinatorLayout.

1.What is CoordinatorLayout

CoordinatorLayout is an enhanced version of FrameLayout, which extends the functionality of FrameLayout so that subviews can better coordinate and interact. It is implemented by using some special Behavior objects. These Behavior objects define the interaction rules between subviews. Single reference to coordinatorLayout does not have much effect. The important thing is coordinatorLayout Use with behavior!

2. Characteristics of CoordinatorLayout

  • Layout hierarchy management: CoordinatorLayout uses Z-axis stacking to manage the display order of subviews. By setting different elevation (Z-axis height) values, you can control the stacking order of subviews.
  • Behaviors: CoordinatorLayout uses Behavior objects to define interactive behaviors between subviews. Each subview can be associated with a Behavior object, which determines how the subview interacts with other subviews.
  • Event distribution processing: CoordinatorLayout can automatically handle touch event conflicts between subviews to avoid event contention and conflicts.

3. Usage of CoordinatorLayout

  1. Use CoordinatorLayout as the parent container in the layout file, and place the subviews that need to be coordinated inside.

  2. Add corresponding Behavior objects to each subview and associate them by setting the app:layout_behavior attribute. For example:

    <?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">
        <TextView
            app:layout_behavior=".FollowBehavior"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Observer" />
        <Button
            android:id="@ + id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="observed"/>
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    Note here that app:layout_behavior=”.FollowBehavior” here is to set .FollowBehavior to the name of the custom Behavior. Different names distinguish different Behaviors. As for the coordination effect of the subviews, it will be implemented in the custom class of the behavior. The class name Need to be consistent with this name

  3. Implement a custom Behavior class (if necessary), inherit from CoordinatorLayout.Behavior, and override the required methods to achieve the required interaction effects. For example:

    public class FollowBehavior extends CoordinatorLayout.Behavior<TextView> {<!-- -->
    
        public FollowBehavior(Context context, AttributeSet attrs) {<!-- -->
            //His construction method
            super(context, attrs);
        }
    
        @Override
    
        public boolean layoutDependsOn(CoordinatorLayout parent, TextView child, View dependency) {<!-- -->
            //This is usually used to determine the dependencies between views. The binding logic here is described below.
            return dependency instanceof Button;
        }
    
        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, TextView child, View dependency) {<!-- -->
            child.setX(dependency.getX() + 150);
            child.setY(dependency.getY() + 150);
            return true;
        }
    }
    

    layoutDependsOn: In this method, the position of the TextView view is associated with the position of the Button view. Note here that instanceof is used to bind the control type. It is not conducive to id binding when binding. Its default The logic is to judge in the view where the behavior is located. As long as a Button control is passed in as dependency and the conditions are met, the dependency will be established. Establish the connection between TextView and Button so that the position of TextView can be adjusted according to the position change of Button in the onDependentViewChanged method.

    If you want to specify a button to be bound to, then do the following:

     return dependency.getId() == R.id.button1
    

onDependentViewChanged: In this method, the position of the button is not changed. The main purpose here is to position the TextView at the y coordinate of the button plus 150 pixels, and the x coordinate plus 150 pixels. The dependency here is the button determined in the above method, and the child is textView

Let’s make the button move

package com.example.coordinatorlayout;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {<!-- -->

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Set a touch event listener. When the user interacts with the button, the code in the listener will be executed.
        findViewById(R.id.btn).setOnTouchListener(new View.OnTouchListener() {<!-- -->
            @Override
            //The callback method of the touch event listener. When the user touches the button, the system will call this method
            public boolean onTouch(View v, MotionEvent event) {<!-- -->
                //Determine whether the action of the touch event is a mobile operation
                if (event.getAction() == MotionEvent.ACTION_MOVE) {<!-- -->
                    //Set the button position to change, v is the button, event refers to the touch position
                    v.setX(event.getRawX() - v.getWidth() / 2);
                    v.setY(event.getRawY() - v.getHeight() / 2);
                }
                return true;
            }
        });

    }
}

4.CoordinatorLayout related attribute methods

Properties of CoordinatorLayout

  • layout_behavior: used to specify the Behavior of the subview, which defines the interaction between the subview and other views.
  • keylines: Defines the position of keylines (keylines) to help align subviews in the layout.

Behavior methods

  • onDependentViewChanged: Used to adjust its own layout when the dependent view changes.

  • layoutDependsOn: Used to determine whether the Behavior depends on another view.

  • onStartNestedScroll and onNestedScroll: used to handle nested scrolling events.

    Methods of CoordinatorLayout

  • addView and removeView: used to add or remove subviews.

  • requestChildFocus and requestChildRectangleOnScreen: used to request the subview to obtain focus or scroll to a specific area.

  • isPointInChildBounds: Used to determine whether a specific coordinate point is within the range of the subview.

4.Usage of CoordinatorLayout

  1. Response to scrolling events: CoordinatorLayout can be used in conjunction with scrollable subviews (such as RecyclerView, NestedScrollView, etc.) to allow other related views to respond when the subview scrolls, such as shrinking and suspending the title bar. Button hiding and other effects.
  2. Coordinate subview layout: By using Behavior to control the position and size of subviews, you can achieve some complex layout interaction effects, such as the linkage effect of other views when dragging a view.
  3. Implement animation effects: You can use the Behavior mechanism of CoordinatorLayout to achieve some complex animation effects. For example, when specific conditions occur, subviews perform translation, scaling, rotation and other animations.
  4. Implement folding layout: You can use AppBarLayout and CollapsingToolbarLayout combined with CoordinatorLayout to achieve the folding and unfolding effect of the header view.
  5. Handling input events: You can use CoordinatorLayout to handle some input events, such as dragging, clicking, etc., and then trigger corresponding operations based on different events.