How to create Horizontal ListView in Android?

AndroidApps/ApplicationsMobile Development

This example demonstrates how do I create Horizontal ListView in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Kindly add the below-given dependence in the Gradle −

implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'

Step 2 − Add the following code to res/layout/activity_main.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:padding="6dp"
   tools:context=".MainActivity">
   <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:layout_centerInParent="true"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
   RecyclerView recyclerView;
   RecyclerView.LayoutManager layoutManager;
   RecyclerView.Adapter adapter;
   ArrayList<String> numberName;
   ArrayList<Integer> numberImage;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      numberName = new ArrayList<>(Arrays.asList("Four...", "Nine... ", "Seven...", "Six...", "Ten...", "Three...", "Two..."));
      numberImage = new ArrayList<>(Arrays.asList(R.drawable.four, R.drawable.nine, R.drawable.seven,
R.drawable.six, R.drawable.ten, R.drawable.three, R.drawable.two));
      // Calling the RecyclerView
      recyclerView = findViewById(R.id.recyclerView);
      recyclerView.setHasFixedSize(true);
      // The number of Columns
      layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
      recyclerView.setLayoutManager(layoutManager);
      adapter = new MyAdapter(MainActivity.this, numberName, numberImage);
      recyclerView.setAdapter(adapter);
   }
}

Step 4 − Create a java class (MyAdapter.java) and add the following code −

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.recyclerview.widget.RecyclerView;
class MyAdapter extends RecyclerView.Adapter <MyAdapter.ViewHolder>{
   private ArrayList<String>numberName;
   private ArrayList<Integer> numberImage;
   private Context context;
   MyAdapter(Context context, ArrayList<String> numberName, ArrayList<Integer> numberImage) {
      super();
      this.context = context;
      this.numberName = numberName;
      this.numberImage = numberImage;
   }
   @Override
   public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
      View v = LayoutInflater.from(viewGroup.getContext())
      .inflate(R.layout.gridlayout, viewGroup, false);
      return new ViewHolder(v);
   }
   @Override
      public void onBindViewHolder(ViewHolder viewHolder, int i) {
         viewHolder.textView.setText(numberName.get(i));
         viewHolder.imgThumbnail.setImageResource(numberImage.get(i));
         viewHolder.setClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int position, boolean isLongClick) {
               if (isLongClick) {
                  Toast.makeText(context, "#" + position + " - " + numberName.get(position) + " (Long
click)", Toast.LENGTH_SHORT).show();
                  context.startActivity(new Intent(context, MainActivity.class));
               } else {
                  Toast.makeText(context, "#" + position + " - " + numberName.get(position),
                  Toast.LENGTH_SHORT).show();
               }
            }
         });
      }
      @Override
      public int getItemCount() {
         return numberName.size();
      }
      public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnLongClickListener {
         ImageView imgThumbnail;
         TextView textView;
         private ItemClickListener clickListener;
         ViewHolder(View itemView) {
            super(itemView);
            imgThumbnail = itemView.findViewById(R.id.imgThumbnail);
            textView = itemView.findViewById(R.id.textView);
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
         }
         void setClickListener(ItemClickListener itemClickListener) {
            this.clickListener = itemClickListener;
         }
         @Override
            public void onClick(View view) {
               clickListener.onClick(view, getPosition(), false);
            }
         @Override
         public boolean onLongClick(View view) {
            clickListener.onClick(view, getPosition(), true);
            return true;
         }
      }
}

Step 5 − Create a layout resource file and following code in listitem

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:card_view="http://schemas.android.com/apk/res-auto"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <androidx.cardview.widget.CardView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="0dp"
      android:layout_marginLeft="5dp"
      android:layout_marginRight="5dp"
      android:layout_marginTop="9dp"
      card_view:cardCornerRadius="3dp"
      card_view:cardElevation="0.01dp">
      <RelativeLayout
         android:id="@+id/topLayout"
         android:layout_width="match_parent"
         android:layout_height="160dp">
         <ImageView
            android:id="@+id/imgThumbnail"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_above="@+id/textView"
            android:layout_centerHorizontal="true"
            android:scaleType="fitXY" />
         <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentStart="true"
            android:layout_gravity="bottom"
            anroid:background="#ff444444"
            android:gravity="center_vertical"
            android:paddingStart="5dp"
            android:paddingEnd="2dp"
            android:text="Test"
            android:textColor="#fff"
            android:textSize="20sp" />
      </RelativeLayout>
   </androidx.cardview.widget.CardView>
</LinearLayout>

Step 6 − Create an Interface (ItemClickListener.java) and add the following code −

import android.view.View;
   interface ItemClickListener {
      void onClick(View view, int position, boolean isLongClick);
   }

Step 7 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
   </activity>
</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the RunPlay Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

raja
Published on 29-Oct-2019 15:24:07
Advertisements