Android CardView - Next/Previous Pagination

December 30, 2017 Oclemy Android CardView 5 minutes, 21 seconds

This example examines how to perform a next/previous pagination in android.

We are going to page/paginate CardViews.

1. Create Project

  1. First create an empty project in android studio. Go to File --> New Project.

  2. Type the application name and choose the company name. New Project Dialog
  3. Choose minimum SDK. Choose minimum SDK
  4. Choose Empty activity. Choose Empty Activity
  5. Click Finish. Finish

This will generate for us a project with the following:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity View.You add your views and widgets here.
2. MainActivity.java Class Your Launcher activity

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component. If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Modify Build.gradle

Add two dependencies in app level build.gradle.

  • App level build.gradle.
  • We specify dependeniceis here, in this case support libraries appcomat and cardview.
  • Our MainActivity will derive from appcompatactivity while we'll be paginating CardViews instances.
    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
    }

3. Create Layouts

activity_main.xml

  • ActivityMain.xml.
  • Our MainActivity layout.
  • To hold our Cards and next/previous buttons.
<?xml version="1.0" encoding="utf-8"?>

<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_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.cardspagination.MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        >
        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/content"
            android:layout_height="500dp"
            android:layout_width="match_parent"
            ></LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <Button
                android:id="@+id/prevBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Previous" />
            <Button
                android:id="@+id/nextBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Next" />

        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

Java Classes

1. Card.java

  • This class represents our custom CardView.
  • It derives android.support.v7.widget.CardView.
  • Our CardView shall have an imageview and a textview.
  • We programmatically instantiate an imageview and textview and add them to our CardView depending on the page shown.
package com.tutorials.hp.cardspagination;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class Card extends CardView {

    public static Card newInstance(Context c,int pos)
    {
        //INSTANTIATE CARD
        Card card=new Card(c);
        card.setCardElevation(10);

        //INSTANTIATE TEXTVIEW
        TextView nameTxt=new TextView(c);
        nameTxt.setPadding(5,5,5,5);
        nameTxt.setTextSize(20);

        //INSTANTIATE IMAGEVIEW
        ImageView img=new ImageView(c);
        img.setPadding(5,5,5,5);
        img.setLayoutParams(new ViewGroup.LayoutParams(400,400));

        //SET WIDGETS TO CARDVIEW DEPENDING ON PAGE
        switch (pos)
        {
            case 0 :
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#009968"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.enterprise);
                card.addView(nameTxt);
                card.addView(img);

                break;
            case 1 :
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#0099e5"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.hubble);
                card.addView(nameTxt);
                card.addView(img);
                break;
            case 2 :
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#ee8600"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.kepler);
                card.addView(nameTxt);
                card.addView(img);
                break;
            case 3 :
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#4caf50"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.spitzer);
                card.addView(nameTxt);
                card.addView(img);
                break;
            case 4 :
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#03a9f4"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.voyager);
                card.addView(nameTxt);
                card.addView(img);
                break;
            default:
                card.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                card.setCardBackgroundColor(Color.parseColor("#009968"));
                nameTxt.setText("Card Page "+String.valueOf(pos));
                img.setImageResource(R.drawable.enterprise);
                card.addView(nameTxt);
                card.addView(img);
        }

        return card;
    }

    public Card(Context context) {
        super(context);
    }
}

2. MainActivity.java

  • Our MainActivity.
  • It derives from AppCompatActivity.
  • Inflated from activity_main.xml.
  • Methods: onCreate()
  • First we create our 5 Card instances here.
  • We handle next/previous pagination of our CardViews here.
package com.tutorials.hp.cardspagination;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //DECLARATIONS.
    ArrayList<Card> cards=new ArrayList<>();
    Button prevBtn,nextBtn;
    LinearLayout layout;
    int i=0;

    //WHEN ACTIVITY IS CREATED.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //INITIALIZE VIEWS
        layout= (LinearLayout) findViewById(R.id.content);
        prevBtn= (Button) findViewById(R.id.prevBtn);
        nextBtn= (Button) findViewById(R.id.nextBtn);
        prevBtn.setEnabled(false);

        //CREATE 5 CARDS
        for(int i=0;i<5;i++)
        {
            cards.add(Card.newInstance(this,i));
        }

        //ADD FIRST CARD TO OUR LAYOUT
        layout.addView(Card.newInstance(this,i));

        //NAVIGATE TO NEXT CARD
        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(i<cards.size())
                {
                    i+=1;
                    layout.removeAllViews();
                    layout.addView(Card.newInstance(MainActivity.this,i));

                    //TOGGLE NEXT/PREVIOUS BUTTONS
                    if(i==cards.size())
                    {
                        nextBtn.setEnabled(false);
                        prevBtn.setEnabled(true);

                    }else
                    {
                        nextBtn.setEnabled(true);
                        prevBtn.setEnabled(true);

                    }
                }

            }
        });
        //NAVIGATE TO PREVIOUS CARD
        prevBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(i>0)
                {
                    i-=1;
                    layout.removeAllViews();
                    layout.addView(Card.newInstance(MainActivity.this,i));

                    //TOGGLE NEXT/PREVIOUS BUTTONS
                    if(i==0)
                    {
                        prevBtn.setEnabled(false);
                        nextBtn.setEnabled(true);

                    }else
                    {
                        prevBtn.setEnabled(true);
                        nextBtn.setEnabled(true);

                    }
                }
            }
        });
    }
}

Comments