Main navigation

Android ScrollView Tutorial : Android Observablescrollview Example

adsense

Demo Video for Android ScrollView

Android Viewpager Example

So we will first make a ListView from where information will be passed to Android ScrollView through Intent.

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name (We have named as Android Observable ScrollView).
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps. Make sure build.grade has following code specially compile ‘com.android.support:appcompat-v7:23.1.1’:

Make following changes:

Build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.github.ksoichiro:android-observablescrollview:1.5.0'
    compile 'com.nineoldandroids:library:2.4.0'
}

In the above code, last two modules are mandatory. These are responsible for making Android ObservableScrollView. Sync Code now.

Now make we will include image in drawable folder which will be shown at top of Android ScrollView. Copy any image (Ctrl+C) and paste it at path: …/AndroidObservableScrollView/app/src/main/res/drawable . Also we will create two new files in drawable folder i.e. gradient_header_background.xml and sliding_header_overlay.xml .

gradient_header_background.xml

<shape xmlns:android="https://schemas.android.com/apk/res/android">

    <gradient
        android:angle="270"
        android:endColor="#00616161"
        android:startColor="#CC616161" />

</shape>

sliding_header_overlay.xml

<shape xmlns:android="https://schemas.android.com/apk/res/android">

    <gradient
        android:angle="270"
        android:endColor="#00009688"
        android:startColor="#FF009688" />

</shape>

File Structure will look like this:

Android ScrollView

To make a nice looking layout we have to make some changes in colors, dimensions, strings and styles. Now go to path …/AndroidObservableScrollView/app/src/main/res/values and make changes in following files:

colors.xml

<resources>

    <color name="primary">#009688</color>
    <color name="primaryDark">#00796b</color>
    <color name="accent">#eeff41</color>
    <color name="accentLight">#F4FF81</color>

</resources>

dimes.xml

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="margin_standard">16dp</dimen>
    <dimen name="margin_short">8dp</dimen>
    <dimen name="margin_extra_short">4dp</dimen>

    <dimen name="toolbar_elevation">4dp</dimen>

    <dimen name="toolbar_margin_start">72dp</dimen>
    <dimen name="flexible_space_height">72dp</dimen>
    <dimen name="flexible_space_image_height">240dp</dimen>
    <dimen name="flexible_space_show_fab_offset">120dp</dimen>

    <dimen name="parallax_image_height">180dp</dimen>
    <dimen name="tab_height">48dp</dimen>

    <dimen name="header_bar_height">72dp</dimen>
    <dimen name="intersection_height">16dp</dimen>

    <dimen name="sliding_slop">32dp</dimen>
    <dimen name="sliding_overlay_blur_size">4dp</dimen>
</resources>

strings.xml

<resources>

    <string name="app_name">ObservableScrollView for Android</string>
    <string name="title_activity_main">Android ObservableScrollView</string>
    <string name="title_activity_about">About this app</string>

    <string name="title_activity_parallaxtoolbarscrollview">Parallax scrollView &amp; toolbar</string>
    <string name="title_activity_toolbarcontrolscrollview">ScrollView &amp; Toolbar</string>

    <string name="lipsum">With the aim of helping the community, we are providing free and useful resources, information, tips and tricks to learn Android development. We believe that education is a basic human right and hence we seek to make it possible for all people in the world to learn Android development without any hassle. This is one stop solution for both android developers and learners. Here at Android Tutorial Point we thrive to deliver the best tutorials. In this direction, we are trying to create a community that will cater to your needs, whether you are a beginner or a seasoned veteran. Learners can refer our basic tutorials and developers can refer Material Design, Networking and Intermediate tutorials. Stick with us for a while, and we promise you will become an Android Rockstar.Wanna part of this journey? Contact Us. You are most cordially invited to connect with us. Kapil Gupta: Kapil is a technology enthusiast with a wide knowledge base and experience with multiple programming languages. He is currently working with world’s second largest software company. He loves to create and automate stuff. He is fond of working on new and emerging technology. Due to his love for sharing knowledge, he is a part of android tutorial point team. Feel free to contact him on Facebook or LinkedIn. You can also mail him at [email protected] Navneet Goel: Navneet is a Digital Marketing and Coding enthusiast with the heart of an entrepreneur. Passed out of NSIT Delhi in 2014, He is currently working in a multinational company as an RnD Engineer and used to write Android Tutorials in free time. He believes in giving back to society and hence started this blog. You are most welcome to connect with him on Facebook, Twitter or LinkedIn. You can also mail him at [email protected] Android Logo - In 2007, the green Android logo was designed for Google by graphic designer Irina Blok. The design team was tasked with a project to create a universally identifiable icon with the specific inclusion of a robot in the final design. After numerous design developments based on science-fiction and space movies, the team eventually sought inspiration from the human symbol on restroom doors and modified the figure into a robot shape. As Android is open-sourced, it was agreed that the logo should be likewise, and since its launch the green logo has been reinterpreted into countless variations on the original design. Linux kernel - Android variant of the Linux kernel has further architectural changes that are implemented by Google outside the typical Linux kernel development cycle, such as the inclusion of components like Binder, ashmem, pmem, logger, wakelocks, and different out-of-memory handling.</string>

</resources>

In the above code, whatever we have added under string lipsum will be shown under Android ScrollView Text area.

styles.xml

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
    </style>

    <style name="AppTheme.Toolbar" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
    </style>

    <style name="Toolbar" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
    </style>


</resources>

So finally we are done with declaration part. Now comes the most important part of Android ScrollView Tutorial i.e. Layout.

Layout of Android ScrollView

Here we will have to make two layouts, first for Android ListView and second for Android ScrollView. Make following changes in activity_main.xml:

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <android.support.v7.widget.Toolbar
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="@dimen/toolbar_elevation"
        app:popupTheme="@style/Theme.AppCompat.Light.DarkActionBar"
        app:theme="@style/Toolbar"
        >

    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </FrameLayout>
</LinearLayout>

In activity_main.xml Framelayout is responsible for making Android ListView. We will click on list generate an Android ScrollView.

Now comes the layout of Android ScrollView (a.k.a Android Observablescrollview). Create a new layout file named activity_parallaxtoolbarscrollview.xml at path …/AndroidObservableScrollView/app/src/main/res/layout/.

activity_parallaxtoolbarscrollview.xml

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.ksoichiro.android.observablescrollview.ObservableScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/parallax_image_height"
                android:scaleType="centerCrop"
                android:src="@drawable/example" />

            <View
                android:id="@+id/anchor"
                android:layout_width="match_parent"
                android:layout_height="@dimen/parallax_image_height"
                android:minHeight="@dimen/parallax_image_height" />

            <TextView
                android:id="@+id/body"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/anchor"
                android:background="@android:color/white"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:text="@string/lipsum" />
        </RelativeLayout>

    </com.github.ksoichiro.android.observablescrollview.ObservableScrollView>

    <include layout="@layout/gradient_header" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/Theme.AppCompat.Light.DarkActionBar"
        app:theme="@style/Toolbar" />
</FrameLayout>

In the above code we are using Framelayout to overlay Toolbar over Android ObservableScrollView as you could see in image below. After that we are using ObservableScrollView which is primary attribute to be used to make it work. We want to show image and text in Android ScrollView, So we made a child of ObservableScrollView i.e. Relative Layout. In the Relative Layout we have ImageView which is going to have “Parallax” effect and TextView which is the main content of Android ScrollView. We need to move the text and image separately, so we are using their parent as Relative Layout. Finally we are using android:id=”@+id/anchor” in View group. This is important to move Text and image at different speeds. With this anchor view, we can move only ImageView. The anchor View and TextView will remain in their position.

Android ScrollView

We need to add two more layout files to show Description and Class name on ListView. Create following layout files at path …/AndroidObservableScrollView/app/src/main/res/layout.

gradient_header.xml

<View xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@drawable/gradient_header_background"
    android:minHeight="?attr/actionBarSize" />

list_item_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center_vertical"
              android:minHeight="?android:attr/listPreferredItemHeight"
              android:orientation="vertical"
              android:padding="6dp">

    <TextView
        android:id="@+id/className"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Activity class name"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Description of the sample"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

File Structure will look like this:

Android ScrollView
So finally layout structure of our Android ScrollView is complete. Now let’s add some animation in it ;). For adding animation we need ?? Of Course MainActivity.java.

Adding Animation in Android ScrollView

We need two java files for adding animation. First one for ListView and second for Android ScrollView. User will click on ListView and data will be passed to second activity through Intent. This second activity will show Android ScrollView. So let’s start coding it:

MainActivity.java

package com.androidtutorialpoint.androidobservablescrollview;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private static final String CATEGORY_SAMPLES = MainActivity.class.getPackage().getName();
    private static final String TAG_CLASS_NAME = "className";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_INTENT = "intent";

    private ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(android.R.id.list);
        listView.setOnItemClickListener(this);
        refreshData();
    }

    private void refreshData() {
        listView.setAdapter(new SimpleAdapter(this, getData(),
                R.layout.list_item_main,
                new String[]{TAG_CLASS_NAME, TAG_DESCRIPTION,},
                new int[]{R.id.className, R.id.description,}));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem menu) {
        return false;
    }

    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> data = new ArrayList<>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.setPackage(getApplicationContext().getPackageName());
        mainIntent.addCategory(CATEGORY_SAMPLES);

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (list == null) {
            return data;
        }

        addItem(data,
               "ParallaxToolbarScrollViewActivity",
                "Parallax scrollView & toolbar",
                activityIntent(
                        "com.androidtutorialpoint.androidobservablescrollview",
                        "com.androidtutorialpoint.androidobservablescrollview.ParallaxToolbarScrollViewActivity"));

        return data;
    }

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }

    protected void addItem(List<Map<String, Object>> data, String className, String description,
                           Intent intent) {
        Map<String, Object> temp = new HashMap<>();
        temp.put(TAG_CLASS_NAME, className);
        temp.put(TAG_DESCRIPTION, description);
        temp.put(TAG_INTENT, intent);
        data.add(temp);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);

        Intent intent = (Intent) map.get(TAG_INTENT);
        startActivity(intent);
    }
}

In the above code, a List View is created using listView. onItemClick will wait for user to click on ListView and after that data will be passed to second Activity and it started through startActivity(intent). Before passing data refreshData() will be executed which will call getData(). This data will be shown on ListView as shown below:

Android ScrollView

Now comes the main part i.e. Second Activity to show android ObservableScrollView. Create a new java file named ParallaxToolbarScrollViewActivity.java at path …/AndroidObservableScrollView/app/src/main/java/com/androidtutorialpoint/androidobservablescrollview/ and add following code:

ParallaxToolbarScrollViewActivity.java

package com.androidtutorialpoint.androidobservablescrollview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;

public class ParallaxToolbarScrollViewActivity extends AppCompatActivity implements ObservableScrollViewCallbacks {

    private View mImageView;
    private View mToolbarView;
    private ObservableScrollView mScrollView;
    private int mParallaxImageHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parallaxtoolbarscrollview);

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

        mImageView = findViewById(R.id.image);
        mToolbarView = findViewById(R.id.toolbar);
        mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(0, getResources().getColor(R.color.primary)));

        mScrollView = (ObservableScrollView) findViewById(R.id.scroll);
        mScrollView.setScrollViewCallbacks(this);

        mParallaxImageHeight = getResources().getDimensionPixelSize(R.dimen.parallax_image_height);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        onScrollChanged(mScrollView.getCurrentScrollY(), false, false);
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        int baseColor = getResources().getColor(R.color.primary);
        float alpha = Math.min(1, (float) scrollY / mParallaxImageHeight);
        mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(alpha, baseColor));
        ViewHelper.setTranslationY(mImageView, scrollY / 2);
    }

    @Override
    public void onDownMotionEvent() {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
    }
}

In the above code, We are using AppCompatActivity of the v7 appcompat library for the base Activity class, and implement ObservableScrollViewCallbacks. Now initially tool bar should be transparent in Android ScrollView so we are setting its background color to 0 using setBackgroundColor. onScrollChanged() method is used, one of ObservableScrollViewCallbacks, to animate the view. Now we need to translate the ImageView in Y-axis using scrollY parameter and change the alpha value of the background color of the Toolbar using scrollY parameter. Just set the translateY property to half of scrollY as shown below:

Android ScrollView

Also alpha should changes from 0 to 1, but scrollY changes from 0 to thousands, so scrollY should be scaled. You can get more information regarding mathematical formula Math.min(1, (float) scrollY / mParallaxImageHeight); to set alpha in actual documentation of Android Observable ScrollView.

So as text is moved by say ‘x’ image will move by ‘x/2’. This will lead to Parallax in Android ScrollView. Isn’t it amazing ???

Finally scroll state is restored by onRestoreInstanceState.

Don’t forget to update AndroidManifest.xml with the second Activity ParallaxToolbarScrollViewActivity.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.androidobservablescrollview"
          xmlns:android="https://schemas.android.com/apk/res/android"
          xmlns:tools="https://schemas.android.com/tools"
          android:versionCode="5"
          android:versionName="1.3.0">

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="22"
        tools:overrideLibrary="com.melnykov.fab" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".ParallaxToolbarScrollViewActivity"
            android:label="@string/title_activity_parallaxtoolbarscrollview"
            android:theme="@style/AppTheme.Toolbar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="com.androidtutorialpoint.androidobservablescrollview" />
            </intent-filter>
        </activity>

    </application>

</manifest>

So our code of Android ScrollView is complete. You can see demo of this tutorial in the video given at the start of tutorial.



What’s Next ??

You can see our other tutorials on material design like Expandablelistview, ViewPager and GridView Tutorials etc.

We hope you liked our Android ScrollView Tutorial, please leave comments in the comment section below in the case of any doubts.

To download the full code for the Android ScrollView app, Click on the Download Now link below.

Android Firebase Analytics Download Now


Reader Interactions

Comments

    • Hi Abhishek,

      Can you please tell us what error are you getting? We would suggest you to Download code through “Download Now” button and run it in android Studio. It will work for sure. We have tested it. All the best !!

Trackbacks

Leave a Reply

Advertisment ad adsense adlogger