android-logo

ScrollView Horizontal in Android​


ScrollView in Android holds only one direct child. In other words, if you have a complex layout with multiple views, you should include them inside another standard layout. Horizontal ScrollView in Android is used to scroll the elements in horizontal direction. We use android.widget.HorizontalScrollView class functionality for this scroll.

MainActivity.java


package com.androidaura.horizontalscroll;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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">

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/horizontalScrollView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_margin="5dp"
        android:gravity="center">

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="One" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Two" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Three" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Four" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Five" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Six" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Six" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Seven" />

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Eight" />

    </LinearLayout>

    </HorizontalScrollView>

</LinearLayout>
Output
horizontal-scrollview-1
horizontal-scrollview-2

previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.