Click here to Skip to main content
15,867,308 members
Articles / Mobile Apps / Xamarin

Xamarin Android: EventHandlers for ScrollView for Endless Support

Rate me:
Please Sign up or sign in to vote.
4.56/5 (9 votes)
1 Mar 2016CPOL3 min read 21.2K   431   5   2
Scroll View are widely used in Android Layouts. Now when a user scrolls the view, we need to find the scroll event of the scroll view. So this article is all about finding these events across all the Android API Versions.

Introduction

Scroll Views are widely used in Android Layouts. Now-a-days, when user scrolls down, the application usually hides the header or sometimes loads more content on scroll. So there are several uses of having access to ScrollChange event. Now the Android API > 20 provides the implementation to scroll change event of ScrollView but that doesn't works on all devices. I faced this problem when I was in full swing of release as I tested my application on Simulator where the existing implementation works. So we need a robust solution to this. Let's see how we will do that.

Background

The audience to this article can be beginners of Xamarin/Android development. This article will include a very simple application with One Layout and One Activity. Having little knowledge of 'Interfaces' will be addon for the audience. I expect you have set the Xamarin Development Environment. Let's us begin by adding a blank Android Application.

Using the Code

Please read the following steps carefully by adding a new xamrin project or you can make the change in your existing project just by following the steps.

Step 1: Add Project

Add New Project with the following files:

Image 1

As you can see, I have added a blank project with just one Layout that is our Main.axml layout.

Step 2: The Layout

Let's add some content to our view so that we can have some content atleast to make our screen scrollable. So I have added the following layout:

C++
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MainLayout_ScrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000000"
            android:id="@+id/textview1"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="500dp"
            android:background="#FFFFFF"
            android:text="1" />
        <TextView
            android:textColor="#000000"
            android:id="@+id/textview2"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="500dp"
            android:background="#C6C6C6"
            android:text="2" />
    </LinearLayout>
</ScrollView>

About View:

As you can see above, I have firstly added 2 TextViews just to add some content and I gave them height of '500dp' but setting android:layout_height="500dp".

Now, I have the content which has a height of more than my screen resolution height. Hence, if we add a ScrollView, we will have window with scrollable content on it. So, I add a parent Layout as a ScrollView and gave it ID MainLayout_ScrollView1.

Step 3: The Activity

As we know, all our programming part goes to the activity class that is associated with a particular layout. So we have this very basic activity class that implements the above Main.xaml layout. let's have look at the content.

Image 2

 

Step 4: Detect the ScrollView On Scroll Change Event

Now here comes the most important part of our article to add the events to detect if page is scrolled, Now let's first add the following code to our main activity file's OnCreate method.

C#
// Get the ScrollView and add event listner to it
ScrollView MainLayout_ScrollView1 = (ScrollView)FindViewById(Resource.Id.MainLayout_ScrollView1);
MainLayout_ScrollView1.ViewTreeObserver.AddOnScrollChangedListener(this);

As you can see, I have added the scroll change listener to the tree of the scrollview not the scrollview itself.

But this will throw an error as this is just an abstract method we called and still needs to be implemented.

Implement the Interface for TreeViewScrollChangeListener

Let's inherit the class ViewTreeObserver.IOnScrollChangedListener to our main activity class so that we can implement the OnScrollChange method of this interface.

C#
[Activity(Label = "Scroll View Events", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ViewTreeObserver.IOnScrollChangedListener

Definition of the interface

The method that this interface has is the following. You can see it just by pressing F12 once you click on IScrollChangedListener text above.

C#
[Register("android/view/ViewTreeObserver$OnScrollChangedListener", "", 
"Android.Views.ViewTreeObserver/IOnScrollChangedListenerInvoker")]
public interface IOnScrollChangedListener : IJavaObject, IDisposable
{
     [Register("onScrollChanged", "()V", 
	"GetOnScrollChangedHandler:Android.Views.ViewTreeObserver/IOnScrollChangedListenerInvoker, 
	Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
            void OnScrollChanged();
}

Now, we just need to implement this method and write the code to detect the scroll position. SO, just add the following code.

C#
public void OnScrollChanged()
{
   ScrollView MainLayout_ScrollView1 = 
   ((ScrollView)FindViewById(Resource.Id.MainLayout_ScrollView1));
   double scrollingSpace = 
   MainLayout_ScrollView1.GetChildAt(0).Height - MainLayout_ScrollView1.Height;

    if (scrollingSpace <= MainLayout_ScrollView1.ScrollY) // Touched bottom
    {
       // Do the things you want to do
       Toast.MakeText(this, "You have reached to the bottom!", ToastLength.Short);
    }
    else
    {
       //Do the load more like things
    }
}

Step 5: Build & Run

Just build the application and run it. You will see output screen. When you scroll it, on reaching to the bottom of the screen, it will display a toast message.

Output

Points of Interest

We can find a scroll event on the page by a little hack to the TreeViewObserver and can implement an application that is more interactive to user and has better performance.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Puneet Goel is an IT Professional with 8+ years. He is specialized in Microsoft Technologies (Asp.NET, SQL Server, Ajax, Jquery, JavaScript, MVC, and Angular). He is an avid member of several development communities and a serial blogger.He loves to learn new technology, do experiments with existing ones, and always happy to help the community.

Comments and Discussions

 
Generaltnx Pin
sinaf19878-Jul-16 3:03
sinaf19878-Jul-16 3:03 
Questionplease help me, thanks Pin
Seraph_summer8-Apr-16 10:30
Seraph_summer8-Apr-16 10:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.