Click here to Skip to main content
15,880,725 members
Articles / Mobile Apps / Android

Android Horizontal ListView Tutorial

Rate me:
Please Sign up or sign in to vote.
4.33/5 (4 votes)
4 Nov 2016CPOL4 min read 62.6K   9   4
In this horizontal listview Android example, we will discuss how to create a horizontal listview using RecyclerView.

In this horizontal listview Android example, we will discuss how to create a horizontal listview using RecyclerView. Android Horizontal ListView is required in apps where we create product listing as in various shopping apps and Google play store app as shown below.

Android Horizontal ListView Tutorial

We will be creating an Android horizontal listview that will show fruits in a horizontal list. After completion, the app will look like as shown in the Demo Video Below.

Demo for Android Horizontal ListView

Check out the demo here.

Creating a New Project – HorizontalListView

  1. Open Android Studio and create a new project HorizontalListView and company domain application.example.com (We have used our own company domain, i.e., androidtutorialpoint.com. Similarly, you can use yours).
  2. Click Next and choose Min SDK, we have kept the default value. Again Click Next and Choose Blank Activity .
  3. Choose the Activity as MainActivity and click next.
  4. Leave all other things as default and Click Finish.

A new project will be created and gradle will resolve all the dependencies.
We would be listing fruits in our Android horizontal list view so create a new Fruit.java class which will have all the field as well as getter, setter methods required for Fruits. Add the following code to the class:

Fruit.java

Java
package com.androidtutorialpoint.horizontallistview;
public class Fruit {

    String cardName;
    int imageResourceId;
    int isfav;
    int isturned;
 
    public int getIsturned() {
        return isturned;
    }
    public void setIsturned(int isturned) {
        this.isturned = isturned;
    }
    public int getIsfav() {
        return isfav;
    }
    public void setIsfav(int isfav) {
        this.isfav = isfav;
    }
    public String getCardName() {
        return cardName;
    }
    public void setCardName(String cardName) {
        this.cardName = cardName;
    }
    public int getImageResourceId() {
        return imageResourceId;
    }
    public void setImageResourceId(int imageResourceId) {
        this.imageResourceId = imageResourceId;
    }
}

Adding Support Library for RecyclerView

Add the following code to the App Level build.gradle.

Java
compile 'com.android.support:recyclerview-v7:24.0.0'
compile 'com.android.support:cardview-v7:24.0.0'

Now, Gradle will sync your project and add the dependencies.

Add a RecyclerView

Create a layout file by right-clicking on the res/layout directory and selecting New → Layout resource file. Name the file fragment_card.xml and click OK to create the file. Open the file, add the following code:

fragment_card.xml

XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_left_margin"
    android:paddingRight="@dimen/activity_right_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

Let’s create a layout file. Create a new Layout resource file, name it recycle_items.xml and paste the following code.

recycle_items.xml

XML
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/card_height"
        android:orientation="vertical"
        android:weightSum="4">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="3.2"
            android:orientation="vertical">
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal">
                <ImageView
                    android:id="@+id/coverImageView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:scaleType="centerCrop"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="left|bottom"
                  android:background="@android:drawable/screen_background_dark_transparent"
                    android:orientation="vertical">
                    <TextView
                        android:id="@+id/titleTextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="16dp"
                        android:textSize="@dimen/text_size"
                        android:textColor="#FFFFFF"
                        android:textStyle="bold"/>
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="0.8"
            android:gravity="center|right"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/likeImageView"
                android:layout_width="@dimen/icon_width"
                android:layout_height="@dimen/icon_height"
                android:padding="@dimen/icon_padding"
                android:src="@drawable/ic_like" />
            <ImageView
                android:id="@+id/shareImageView"
                android:layout_width="@dimen/icon_width"
                android:layout_height="@dimen/icon_height"
                android:padding="@dimen/icon_padding"
                android:src="@drawable/ic_share" />
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

In the Layout, we have a LinearLayout and FrameLayout. We have an ImageView for the Android horizontal listview background and a TextView for displaying the name of the fruit. We have another LinearLayout for the Like and Share buttons.

Adding the Functionality to Horizontal ListView Android Example App

  1. Create a new fragment, name it HorizontalListViewFragment.java and add the following code.
    We will use the array to store the name and image of the fruit. Download the horizontal listview Android example by clicking on the Download Now Button above, add the photos of fruits to the drawable folder.

    HorizontalListViewFragment.java

    Java
    String Fruits[] = {"Mango","Apple",
    		"Grapes","Papaya","WaterMelon"};
    int  Images[] = {R.drawable.mango,R.drawable.apple,
    R.drawable.grapes,R.drawable.papaya,R.drawable.watermelon};
  2. In the onCreate() method, we use the initializeList() method to initialize the ArrayList in Android Cardview which will be passed to the Adapter later.
    Java
         @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            listitems.clear();
            for(int i =0;i<Fruits.length;i++){
                Fruit item = new Fruit();
                item.setCardName(Fruits[i]);
                item.setImageResourceId(Images[i]);
                item.setIsfav(0);
                item.setIsturned(0);
                listitems.add(item);
            }
    
            getActivity().setTitle("Fruits");
    }
    
  3. Next, add view Holder for Android horizontal listview to hold on to the views, so add the following code.
    Java
    public class MyViewHolder extends RecyclerView.ViewHolder {
    
        public TextView titleTextView;
        public ImageView coverImageView;
        public ImageView likeImageView;
        public ImageView shareImageView;
    
        public MyViewHolder(View v) {
            super(v);
            titleTextView = (TextView) v.findViewById(R.id.titleTextView);
            coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
            likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
            shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
            likeImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int id = (int)likeImageView.getTag();
                    if( id == R.drawable.ic_like){
    
                        likeImageView.setTag(R.drawable.ic_liked);
                        likeImageView.setImageResource(R.drawable.ic_liked);
    
                        Toast.makeText(getActivity(),titleTextView.getText()+"
                        added to favourites",Toast.LENGTH_SHORT).show();
    
                    }else{
                        likeImageView.setTag(R.drawable.ic_like);
                        likeImageView.setImageResource(R.drawable.ic_like);
                        Toast.makeText(getActivity(),titleTextView.getText()+"
                        removed from favourites",Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
            shareImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
                            "://" + getResources().getResourcePackageName(coverImageView.getId())
                            + '/' + "drawable" + '/' +
                            getResources().getResourceEntryName((int)coverImageView.getTag()));
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
                    shareIntent.setType("image/jpeg");
                    startActivity(Intent.createChooser
                    (shareIntent, getResources().getText(R.string.send_to)));
                }
            });
        }
    }
    

    The above class will have a reference of ImageView and the TextViews for each horizontal listview it will be holding. We have also attached the setOnClickListener() to the likeImageView and the shareImageView.

    On clicking the like button, the state of the button is toggled and it shows a corresponding message that it has added/removed the item to/from favorites.

    In the OnClick() for the shareImageView, an Intent is fired that shows an option to share the image of the place you have selected.

  4. Next, we extend the RecyclerView.Adapter class, this adapter is link between the RecyclerView and the data which we want to list. It creates required ViewHolders and also binds the ViewHolder to data from the Fruit class.

    It has three main methods:

    1. onCreateViewHolder(): Inflates the layout and creates a new view Holder.
    2. onBindViewHodler(): Binds the data to the view holder.
    3. getItemCount(): Returns the size of the data to be displayed.

    Use the following code to create a MyAdapter:

    Java
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private ArrayList<Fruit> list;
        public MyAdapter(ArrayList<Fruit> Data) {
            list = Data;
        }
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
            // create a new view
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycle_items, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            return holder;
        }
        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
    
            holder.titleTextView.setText(list.get(position).getCardName());
            holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
            holder.coverImageView.setTag(list.get(position).getImageResourceId());
            holder.likeImageView.setTag(R.drawable.ic_like);
    
        }
        @Override
        public int getItemCount() {
            return list.size();
        }
    }
    
  5. In the onCreateView() method of the HorizontalListViewFragment.java, create a new LinearLayoutManager and set the RecyclerView to use it. The purpose of the LayoutManager is to handle the positioning of the list items and scrolling behaviour.

    Note that we are setting the orientation to HORIZONTAL in the LinearLayoutManager for the horizontal listview behaviour.

    Java
    @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                Bundle savedInstanceState) {
    
           View view = inflater.inflate(R.layout.fragment_horizontal_list_view, container, false);
           MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
           MyRecyclerView.setHasFixedSize(true);
           LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
           MyLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
           if (listitems.size() > 0 & MyRecyclerView != null) {
               MyRecyclerView.setAdapter(new MyAdapter(listitems));
           }
           MyRecyclerView.setLayoutManager(MyLayoutManager);
    
           return view;
       }
    

    Here is the completed HorizontalListViewFragment.java file => HorizontalListViewFragment.java href=”http://www.androidtutorialpoint.com/wp-content/uploads/2016/11/HorizontalListViewFragment.txt”>HorizontalListViewFragment.java

  6. Next, host the HorizontalListViewFragment in the MainActivity. Open MainActivity.java and add the following code.

    MainActivity

    Java
    package com.androidtutorialpoint.horizontallistview;
    
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v7.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
    
            if (fragment == null) {
                fragment = new HorizontalListViewFragment();
                ;
                fm.beginTransaction()
                        .add(R.id.fragmentContainer, fragment)
                        .commit();
            }
        }
    }

    The layout file for MainActivity, i.e., activity_main.xml consists of a FrameLayout as a fragmentContainer.

    activity_main.xml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    </FrameLayout>

    Run the App and you should see Android horizontal listview which scrolls horizontally and shows your favorite fruits. Try scrolling through horizontal listview Android example and clicking on Like and Share to share the photo. Isn’t this simple ?? Please comment in case you have any doubts or suggestions.

License

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


Written By
Software Developer (Senior)
India India
Hello Developer!

As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I hope you get the best possible value at of our platform. Stick with us for a while, and we promise you will become an $$Android Rockstar$$!

Android Tutorial Point is the right platform if you want to learn about android development. We have a broad collection of tutorials on different aspects of Android Development and it is growing rapidly. 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. For the beginners that are getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how to start with Android programming.


All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for latest android tutorials. You can reach out to us at our Facebook page https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at androidtutorialspoint@gmail.com

Comments and Discussions

 
QuestionThe issues were in HorizontalListViewFragment. Pin
Julian B Dinkins18-Feb-18 20:05
Julian B Dinkins18-Feb-18 20:05 
QuestionThis just straight up doesn't work - Don't bother! Pin
Member 1348921127-Oct-17 3:23
Member 1348921127-Oct-17 3:23 
Question.. Pin
bogel bogel17-Dec-16 19:51
bogel bogel17-Dec-16 19:51 
not enough
QuestionNo down load Pin
limelect10-Nov-16 19:07
limelect10-Nov-16 19:07 

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.