SoFunction
Updated on 2025-04-15

Implementing the scrolling head hover effect based on Android

In many apps, in order to improve the user experience, an effect is needed: when the page content is scrolled, the header area (title bar, navigation bar, etc.) can be hovered at the top and is always visible, while other content continues to scroll. This article will explain in detail how to achieve this scrolling head hover effect in Android, and provide complete source code for easy learning and practical applications.

1. Project background and technical principles

1.1 Background Introduction

In many scenarios, such as e-commerce homepage, news list or data display page, in order to increase the hierarchy of the page and facilitate user navigation, we hope that the head of the page (usually including titles, tabs, navigation buttons, etc.) can always be fixed at the top of the screen when the content is scrolled, and the content area can be scrolled freely. Implementing this effect will help improve the user experience and reduce the hassle of users looking for navigation information during scrolling.

1.2 Technical Principles

There are many solutions to achieve the effect of rolling head hovering. Here are two common methods:

Using CoordinatorLayout + AppBarLayout/CollapsingToolbarLayout:

Android provides components such as CoordinatorLayout and AppBarLayout. It can be easily achieved by coordinating the scroll monitoring and folding toolbar. Suitable for more complex interactive animations, such as picture folding, transformation, etc.

Custom layout and scrolling listening:

If the requirements are simple, you can also use an outer container (such as RelativeLayout or FrameLayout) to include a static header View and a scroll container (such as ScrollView or RecyclerView) to monitor the scrolling state through code, adjust the position of the content, or dynamically hide/display the header. The examples provided later in this article are demonstrated in this way.

In the following example, we construct a custom layout that includes two parts:

  • Static fixed head View
  • NestedScrollView (or ScrollView) that wraps the content, the content is separated from the header when scrolling

At the same time, we monitor the scrolling event to judge that when the content scrolls to the head position, the effect of hovering the head is achieved.

2. Project design and implementation ideas

2.1 Layout Design

Using FrameLayout as the root layout, superimpose two levels in FrameLayout:

  • Top hover area (Header): Fixed at the top of the screen and does not scroll with content.
  • Scroll content area (ScrollView or NestedScrollView): You can place long lists or a large number of controls inside, which users can view through scrolling.

Pay attention to the layout:

  • Make sure the top hover area is placed on the top level to avoid being blocked by the rolling area.
  • Handle the margins between the two areas to make the interface beautiful.

2.2 Code implementation ideas

The following steps are mainly included in the Java code implementation:

Initialize interface controls: Bind the header View and scroll container in XML.

Add scroll listening: Add a scroll listener to the scroll view to detect the current scroll position.

Adjust the head position (or style): When the content scrolls beyond the head height, the head is fixed to display; restored when rolled back to the original position (in this case the head is always fixed, so it is mainly to demonstrate the hover effect).

Compatibility issues: To ensure that the results are consistent on different versions of Android, you can use NestedScrollView to replace the ScrollView for better scroll event support.

2.3 Implementation method selection

The example given here is a simple static layout method, using NestedScrollView to place a large amount of content, and then fixing the head with FrameLayout. In complex scenarios, technologies such as RecyclerView and ItemDecoration can also be combined to achieve more flexible hovering effects.

At the same time, our code is all integrated and detailed Chinese annotations are provided to facilitate everyone to understand the purpose of each line of code. The complete code implementation is shown below.

3. Complete code example

The following code consists of two parts: Java file and XML layout file.

3.1 Java Code ()

/*
  * ==============================================================================================
  * File name:
  * Project name: StickyHeaderDemo
  * Created date: 2025-04-14
  * Author: Katie
  * Description: This file demonstrates how to achieve a scrolling head hover effect in Android.
  * Use FrameLayout as the root layout, which contains fixed header View and
  * A NestedScrollView as the scrolling content area.  By listening for scrolling events,
  * Achieve the effect of always hovering the head over the top of the screen.  Detailed comments help readers understand the code.
  * ==============================================================================================
  */
 
package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class MainActivity extends AppCompatActivity {
 
    // Define log tags    private static final String TAG = "StickyHeader";
 
    // Declare the header View and scroll view    private TextView tvHeader;
    private NestedScrollView scrollView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        // Load the layout file activity_main.xml        setContentView(.activity_main);
 
        // Initialize the view object        tvHeader = findViewById(.tv_header);
        scrollView = findViewById(.nested_scroll_view);
 
        // Add scroll listening to realize monitoring of scroll position (the response logic can be extended here)        (new () {
            /**
              * Callback this method when NestedScrollView scrolls
              * @param v Current scroll view
              * @param scrollX Current horizontal scroll position
              * @param scrollY Current vertical scroll position
              * @param oldScrollX previous horizontal scroll position
              * @param oldScrollY The vertical scroll position before
              */
            @Override
            public void onScrollChange(@NonNull NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // Output log to view the current scrolling position                (TAG, "scrollY: " + scrollY);
                /*
                  * More logic can be added here, such as changing the head style or transparency based on the scroll distance,
                  * But in this example our head View is always fixed above and does not scroll with the content.
                  */
            }
        });
 
        // Initialize scrolling content and load simulated data        initContent();
    }
 
    /**
      * Method name: initContent
      * Function description: Simulate loading a large amount of content into the scrolling area, which is convenient for demonstrating the scrolling head hover effect
      */
    private void initContent() {
        // Find the content TextView and construct the long text        TextView tvContent = findViewById(.tv_content);
        StringBuilder content = new StringBuilder();
        for (int i = 1; i <= 50; i++) {
            ("Lesson").append(i).append("Line Data: This is a sample piece for testing, showing the effect when scrolling.\n");
        }
        (());
    }
}

3.2 XML layout file (activity_main.xml)

<!--
    =====================================================================
    File name:activity_main.xml
    Project name:StickyHeaderDemo
    Creation date:2025-04-14
    author:Katie
    describe:This layout file uses FrameLayout As root layout,Contains a head hover area and a
    NestedScrollView Used to place scrolling content。The head area is always fixed to the top of the screen,The content area can be scrolled。
    =====================================================================
-->
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:andro
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <!-- Fix the head area -->
    <TextView
        android:
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#FF9800"
        android:text="I'm a Sticky Header"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        android:gravity="center"
        android:elevation="4dp"
        android:layout_gravity="top" />
 
    <!-- Scroll content area,Contains long text to demonstrate scrolling effect -->
    <
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="60dp">
        <!-- Content container,use LinearLayout Vertical arrangement -->
        <LinearLayout
            android:
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">
 
            <!-- Sample text area,Load dynamic long text -->
            <TextView
                android:
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Scrolling content is loading..."
                android:textSize="16sp"
                android:textColor="#333333" />
        </LinearLayout>
    </>
 
</FrameLayout>

4. Code interpretation

4.1 Layout structure description

Root layout

Using FrameLayout makes it easy to overlay two subviews together. The head area is always at the top level with layout_gravity="top" while the NestedScrollView avoids the head area by setting layout_marginTop="60dp" to ensure that the content is not obscured by the head.

2. Fix the head View

tv_header sets a higher background color contrast and a larger height, and sets an elevation to make the hover effect more obvious. This View is always fixed at the top of the screen and does not change as you scroll.

3. Scroll container (NestedScrollView)

The use of NestedScrollView is to better support nested scrolling and listening for scrolling change events. The internal LinearLayout is convenient for placing a large amount of test content.

4.2 Java code description

method

In the onCreate method, load the XML layout through setContentView, bind the header and scroll view, and add scroll listening. The listener can expand more interactions based on the scrollY value (such as modifying the head transparency or dynamically changing the background color).

method

This method dynamically generates long text data (50 lines of sample data) in the content area to demonstrate the effect when scrolling. In actual projects, it can be replaced with actual data, list components, or other complex control combinations.

3. Scroll monitoring

NestedScrollView provides an onScrollChange listening method, where the log is simply output. In actual applications, the head can be animation effects, dynamic data refresh, etc. according to the scroll position.

4. Code Author Comments

Each key code is accompanied by a comment indicating the code author "Katie", which is convenient for everyone to refer to and modify later.

5. Project expansion thinking

This article implements a relatively basic rolling head hover effect. The following extended functions can be considered in the future:

Animation effect: Change head transparency, font color or zoom effect according to the scroll distance gradient;

Dynamic data loading: combine RecyclerView and DiffUtil to implement pull-up loading of lists and real-time data updates;

Multi-head applications: implement multiple regions hovering under complex layouts, such as classification tags, toolbars and paging navigation bars working together;

Compatibility optimization: With the help of CoordinatorLayout and AppBarLayout, we can achieve smoother interaction and linkage animations, which are suitable for more complex design needs.

The above is the detailed content of implementing the scrolling head hover effect based on Android. For more information about Android's scrolling head hover, please follow my other related articles!