RecyclerView In Android


RecyclerView In Android
RecyclerView In Android


In this tutorial you will learn how to use RecyclerView in Android.Android RecyclerView is more advanced version of ListView also it gives a better performance. RecyclerView is mostly used to design the user interface with the fine-grain control over the lists and grids of android application.If you like to connect login with this application please view my blog regarding login using android.

For this tutorial you have to make an drawer activity.So create a drawer activity and named as dashboard.

In this tutorial we are going to learn how to render a simple RecyclerView with a custom layout. We’ll also learn how to create an adapter class. The RecyclerView we are going to design contains list with images ,a textview which contains name and also a id ,which is invisible.Lets check the code of the activity_dashboard2.xml (save the xml file as activity_dashboard2.xml).



<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_dashboard"                                                             → Point 1
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_dashboard"                                   → Point 2
app:menu="@menu/activity_dashboard2_drawer" />                                    → Point 3
</androidx.drawerlayout.widget.DrawerLayout>


Point 1:


Here app_bar_dashboard is included , save the app_bar_dashboard in layout.Lets check the code below(save the file as app_bar_dashboard.xml in layout folder):-


<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".dashboard">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.AppCompat.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/Theme.AppCompat.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_dashboard" />                                      → Point 4
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Point 2:


nav_header_dashboard is included ,which you need to save within layout folder(Save the file as nav_header_dashboard.xml).Lets check the code:

<?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"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/nav_header_desc"
android:paddingTop="@dimen/nav_header_vertical_spacing"
app:srcCompat="@mipmap/ic_launcher_round" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/nav_header_title"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/nav_header_subtitle" />
</LinearLayout>


Point 3:

You need to add activity_dashboard2_drawer under menu so that the menu can be added in the dashboard.Save the xml file as activity_dashboard2_drawer.xml .Lets check the code below:-

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="@+id/aq"
android:icon="@drawable/ic_menu_camera"
android:title="@string/menu_home" />
<item
android:id="@+id/de"
android:icon="@drawable/ic_menu_gallery"
android:title="@string/menu_gallery" />
<item
android:id="@+id/vd"
android:icon="@drawable/ic_menu_slideshow"
android:title="@string/menu_slideshow" />
<item
android:id="@+id/sd"
android:icon="@drawable/ic_menu_manage"
android:title="@string/menu_tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_menu_share"
android:title="@string/menu_share" />
<item
android:id="@+id/nav_send"
android:icon="@drawable/ic_menu_send"
android:title="@string/menu_send" />
</menu>
</item>
</menu>

Point 4:

     Save content_dashboard under layout folder as content_dashboard.xml  .Lets check the code:-


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="MissingConstraints">

        <RelativeLayout
            android:id="@+id/lin1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="40dp"
            android:scrollbars="horizontal">


            <ImageView
                android:id="@+id/imageView8"
                android:layout_width="200dp"
                android:layout_height="150dp"
                android:backgroundTint="#80FFFFFF"
                android:backgroundTintMode="src_over"

                android:padding="20dp"
                app:srcCompat="@drawable/fruits2"                       → Image 1
                tools:layout_editor_absoluteX="6dp"
                tools:layout_editor_absoluteY="5dp" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@id/imageView8"
                android:layout_alignTop="@id/imageView8"
                android:layout_alignRight="@id/imageView8"
                android:layout_alignBottom="@id/imageView8"
                android:layout_margin="1dp"
                android:background="#ddffffff"
                android:gravity="center"
                android:text="Fish"
                android:textColor="#FF0000"
                android:textSize="20dp" />


            <ImageView
                android:id="@+id/imageView9"
                android:layout_width="200dp"
                android:layout_height="150dp"
                android:layout_toRightOf="@id/imageView8"
                android:padding="20dp"
                app:srcCompat="@drawable/mix"                          → Image 2
                tools:layout_editor_absoluteX="6dp"
                tools:layout_editor_absoluteY="5dp" />


            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@id/imageView9"
                android:layout_alignTop="@id/imageView9"
                android:layout_alignRight="@id/imageView9"
                android:layout_alignBottom="@id/imageView9"
                android:layout_marginStart="1dp"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="-1dp"
                android:layout_marginEnd="1dp"
                android:layout_marginRight="-2dp"
                android:layout_marginBottom="3dp"
                android:background="#ddffffff"
                android:gravity="center"
                android:text="Meat"
                android:textColor="#FF0000"
                android:textSize="20dp"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/imageView10"
                android:layout_width="200dp"
                android:layout_height="150dp"
                android:layout_toRightOf="@id/imageView9"
                android:padding="20dp"
                app:srcCompat="@drawable/fruits2"                      → Image 3
                tools:layout_editor_absoluteX="6dp"
                tools:layout_editor_absoluteY="5dp" />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@id/imageView10"
                android:layout_alignTop="@id/imageView10"
                android:layout_alignRight="@id/imageView10"
                android:layout_alignBottom="@id/imageView10"
                android:layout_margin="1dp"
                android:background="#ddffffff"
                android:gravity="center"
                android:text="Meat"
                android:textColor="#FF0000"
                android:textSize="20dp" />


        </RelativeLayout>
    </HorizontalScrollView>


    <RelativeLayout
        android:id="@+id/lin2"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_marginTop="150dp"
        android:layout_marginBottom="180dp"
        app:layout_constraintBottom_toTopOf="@+id/card_view_recycler_list"
        app:layout_constraintTop_toBottomOf="@+id/horizontalScrollView"
        app:layout_constraintVertical_bias="0.4"
        tools:layout_editor_absoluteX="0dp">

        <TextView
            android:id="@+id/admintext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="monospace"
            android:text="@string/msgfromadmin"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textStyle="bold"
            android:typeface="sans" />

        <TextView
            android:id="@+id/categories"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/admintext"
            android:paddingTop="20dp"
            android:text="Categories"
            android:textColor="#FF0000"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textStyle="bold"
            android:typeface="sans"
            android:textSize="15dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/card_view_recycler_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="350dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>



Download some images and save in res/drawable folder ,in this code name of the images are
fruits2 and mix.You can give any name in place of image 1,image 2 and image 3 .

Save the following file as shown below:-

activity_card_view.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android">


 <androidx.recyclerview.widget.RecyclerView     android:id="@+id/card_view_recycler_list"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:layout_marginTop="250dp"     app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_card_view_item.xml


<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_margin="10dp"    app:cardCornerRadius="8dp"    app:cardElevation="10dp">

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">

        <ImageView            android:id="@+id/card_view_image"            android:layout_width="match_parent"            android:layout_height="100dp"            android:scaleType="centerCrop"/>

        <TextView            android:id="@+id/card_view_image_title"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_margin="10dp"            android:layout_gravity="center_horizontal"            android:textSize="20dp"/>

        <TextView            android:id="@+id/id1"
            android:layout_width="wrap_content"            android:layout_height="wrap_content"          />


    </LinearLayout>

</androidx.cardview.widget.CardView>



activity_dashboard.xml

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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=".dashboard">

</androidx.constraintlayout.widget.ConstraintLayout>


listing.xml



<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    >

    <ImageView        android:id="@+id/img1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />

    <TextView        android:id="@+id/textView5"        android:layout_width="wrap_content"        android:layout_height="wrap_content"
        android:text="Item Name::"        android:textAppearance="@style/TextAppearance.AppCompat.Button"        android:textColor="@color/colorPrimary"/>

    <TextView        android:id="@+id/textView6"        android:layout_width="wrap_content"        android:layout_height="wrap_content"
        android:text="Item Name::"        android:textAppearance="@style/TextAppearance.AppCompat.Button"        android:textColor="@color/colorPrimary"/>
</LinearLayout>



populatelist.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">




    <ImageView        android:id="@+id/img1"        android:layout_width="fill_parent"        android:layout_height="200dp"        android:scaleType="centerCrop"        android:layout_marginTop="20dp" />

    <TextView        android:id="@+id/sub"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/img1"        android:text="TextView"        android:textColor="@color/colorPrimary" />
    <TextView        android:id="@+id/date"        android:layout_width="260dp"        android:layout_height="wrap_content"        android:layout_below="@+id/sub"        android:text="TextView"        android:textColor="@color/colorPrimary" />

    <TextView        android:id="@+id/amount"        android:layout_width="250dp"        android:layout_height="wrap_content"        android:layout_alignStart="@+id/sub"        android:layout_below="@id/date"        android:text="TextView"        android:textColor="@color/colorPrimary" />
</RelativeLayout>



Save dashboard.xml file under menu.


<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item        android:id="@+id/action_settings"        android:orderInCategory="100"        android:title="@string/action_settings"        app:showAsAction="never" />
</menu>


There will be some .xml file which will be saved under values.Files are as below:-

1.dimens.xml

<?xml version="1.0" encoding="utf-8"?><resources>

    <!--dimes for design 3-->    <dimen name="headerTextSize">22sp</dimen>
    <dimen name="newsMoreTextSize">12sp</dimen>
    <dimen name="loginCardRadius">20dp</dimen>
    <dimen name="loginViewsMargin">20dp</dimen>

    <dimen name="signup_text_margin_top">10dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="nav_header_vertical_spacing">8dp</dimen>
    <dimen name="nav_header_height">176dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

</resources>


Now lets create the java files.

1.dashboard.java



//In this code drawerlayout activity is usedpackage com.example.login;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Menu;
import java.util.ArrayList;
import java.util.List;

public class dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener  {

    private AppBarConfiguration mAppBarConfiguration;
    private List<CarRecyclerViewItem> cardItemList = null;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard2);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        //new code        setTitle("The Title You want to display");
        initializeCarItemList();//this function is called        // Create the recyclerview.        RecyclerView carRecyclerView = (RecyclerView)findViewById(R.id.card_view_recycler_list);
        // Create the grid layout manager with 2 columns.        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        // Set layout manager.        carRecyclerView.setLayoutManager(gridLayoutManager);
        // Create car recycler view data adapter with car item list.        CarRecyclerViewDataAdapter carDataAdapter = new CarRecyclerViewDataAdapter(cardItemList);
        // Set data adapter.        carRecyclerView.setAdapter(carDataAdapter);
    }



    private void initializeCarItemList()
    {
        if(cardItemList == null)
        {
            cardItemList = new ArrayList<CarRecyclerViewItem>();
            cardItemList.add(new CarRecyclerViewItem("Fruites", R.drawable.fruits2,1));
            cardItemList.add(new CarRecyclerViewItem("Vegetables", R.drawable.mix,2));
            cardItemList.add(new CarRecyclerViewItem("Grocery", R.drawable.fruits2,3));
            cardItemList.add(new CarRecyclerViewItem("Fish & Meat", R.drawable.mix,4));
            cardItemList.add(new CarRecyclerViewItem("Land Rover", R.drawable.fruits2,5));
            cardItemList.add(new CarRecyclerViewItem("Future", R.drawable.mix,6));
        }
    }
    @Override    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.dashboard, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();
        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

//check whether the internet is available or not    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.        int id = item.getItemId();
        Boolean stat=isNetworkAvailable();
        if(stat==true) {
            //here we are checking the ids            if (id == R.id.aq) {
                // call the intent CardViewActivity                Intent intent = new Intent(dashboard.this, CardViewActivity.class);
                startActivity(intent);

            } else if (id == R.id.de) {
                // Intent intent=new Intent(MainActivity.this,dailyexpense.class);                //startActivity(intent);
            } else if (id == R.id.vd) {
                //Intent intent=new Intent(MainActivity.this,viewexpense.class);               // Intent intent = new Intent(dashboard.this, Realtime.class);                //startActivity(intent);
            } else if (id == R.id.sd) {
                //Intent intent=new Intent(dashboard.this,offices.class);                //startActivity(intent);
            }
        }
        else        {
            //if there is no internet than call the nonet class ,where an image will be displayed            Intent int1=new Intent(this,nonet.class);
            startActivity(int1);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


2.Save this java file as CardViewActivity.java

package com.example.login;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.List;

public class CardViewActivity extends AppCompatActivity {

    private List<CarRecyclerViewItem> cardItemList = null;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_view);
        setTitle("The Title You want to display");
        initializeCarItemList();
        // Create the recyclerview.        RecyclerView carRecyclerView = (RecyclerView)findViewById(R.id.card_view_recycler_list);
        // Create the grid layout manager with 2 columns.        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        // Set layout manager.        carRecyclerView.setLayoutManager(gridLayoutManager);
        // Create car recycler view data adapter with car item list.        CarRecyclerViewDataAdapter carDataAdapter = new CarRecyclerViewDataAdapter(cardItemList);
        // Set data adapter.        carRecyclerView.setAdapter(carDataAdapter);


    }

    /* Initialise car items in list. */    private void initializeCarItemList()
    {
        if(cardItemList == null)
        {
            cardItemList = new ArrayList<CarRecyclerViewItem>();
            cardItemList.add(new CarRecyclerViewItem("Fruites", R.drawable.fruits2,1));
            cardItemList.add(new CarRecyclerViewItem("Vegetables", R.drawable.mix,2));
            cardItemList.add(new CarRecyclerViewItem("Grocery", R.drawable.fruits2,3));
            cardItemList.add(new CarRecyclerViewItem("Fish & Meat", R.drawable.mix,4));
            cardItemList.add(new CarRecyclerViewItem("Land Rover", R.drawable.fruits2,5));
            cardItemList.add(new CarRecyclerViewItem("Future", R.drawable.mix,6));
        }
    }


}

3. CarRecyclerViewDataAdapter.java


package com.example.login;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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 android.widget.Toast;


import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;

import java.util.List;

public class CarRecyclerViewDataAdapter extends RecyclerView.Adapter<CarRecyclerViewItemHolder> implements View.OnClickListener {

    private List<CarRecyclerViewItem> carItemList;
    TextView carTitleView;
    TextView cardid;
     ImageView carImageView;
    public CarRecyclerViewDataAdapter(List<CarRecyclerViewItem> carItemList) {
        this.carItemList = carItemList;
    }
    @Override    public CarRecyclerViewItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Get LayoutInflater object.        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        // Inflate the RecyclerView item layout xml.        final View carItemView = layoutInflater.inflate(R.layout.activity_card_view_item, parent, false);
        // Get car title text view object.         carTitleView = (TextView) carItemView.findViewById(R.id.card_view_image_title);
         cardid = (TextView) carItemView.findViewById(R.id.id1);
        // Get car image view object.        carImageView = (ImageView) carItemView.findViewById(R.id.card_view_image);
        // When click the image.      //  carItemView.setOnClickListener(this);        //carImageView.setOnClickListener(this);        // Create and return our custom Car Recycler View Item Holder object.        CarRecyclerViewItemHolder ret = new CarRecyclerViewItemHolder(carItemView);

        return ret;
    }

    @Override    public void onBindViewHolder(CarRecyclerViewItemHolder holder, int position) {

        if (carItemList != null) {
            // Get car item dto in list.            CarRecyclerViewItem carItem = carItemList.get(position);

            if (carItem != null) {
                // Set car item title.                holder.getCarTitleText().setText(carItem.getCarName());
                // Set car image resource id.                holder.getCarImageView().setImageResource(carItem.getCarImageId());
                holder.getCardid().setText(carItem.getCardid()+"");
            }



        }
    }

    @Override    public int getItemCount() {
        int ret = 0;
        if (carItemList != null) {
            ret = carItemList.size();
        }
        return ret;
    }

    @Override    public void onClick(View v) {
                // Get car title text.
            }



}


4. CarRecyclerViewItem.java


package com.example.login;
public class CarRecyclerViewItem {

    // Save car name.    private String carName;

    // Save car image resource id.    private int carImageId;
    private int cardid;

    public CarRecyclerViewItem(String carName, int carImageId, int cardid) {
        this.carName = carName;
        this.carImageId = carImageId;
        this.cardid=cardid;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public int getCarImageId() {
        return carImageId;
    }

    public void setCarImageId(int carImageId) {
        this.carImageId = carImageId;
    }

    public int getCardid() {
        return cardid;
    }

    public void setCardid(int cardid) {
        this.cardid = cardid;
    }
}

5. CarRecyclerViewItemHolder.java



package com.example.login;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

public class CarRecyclerViewItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{


    private TextView carTitleText = null;
    private TextView cardid = null;
    private ImageView carImageView = null;

    public CarRecyclerViewItemHolder(View itemView) {
        super(itemView);


        if(itemView != null)
        {
            carTitleText = (TextView)itemView.findViewById(R.id.card_view_image_title);
            cardid = (TextView)itemView.findViewById(R.id.id1);
            carImageView = (ImageView)itemView.findViewById(R.id.card_view_image);
        }
        itemView.setOnClickListener(this);
    }

    public TextView getCarTitleText() {
        return carTitleText;
    }

    public ImageView getCarImageView() {
        return carImageView;
    }
    public TextView getCardid() {
        return cardid;
    }

    @Override    public void onClick(View v) {
        int pos=getLayoutPosition();

        /*Intent intentBundle=new Intent(v.getContext(),viewimage.class);        Bundle bundle=new Bundle();        bundle.putString("title",getCarTitleText().getText().toString());        bundle.putString("id",getCardid().getText().toString());        intentBundle.putExtra("data",bundle);        v.getContext().startActivity(intentBundle);        Log.d("Msg",getCarTitleText().getText().toString());*/        Toast.makeText(itemView.getContext(), "position = " +getCarTitleText().getText().toString(), Toast.LENGTH_SHORT).show();
    }
}

6. now lets check AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.login">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <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/Theme.AppCompat"        android:usesCleartextTraffic="true">
        <activity android:name=".viewimage"></activity>
        <activity android:name=".CardViewActivity"></activity>
        <activity            android:name=".dashboard"            android:theme="@style/Theme.AppCompat.NoActionBar"
             />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <uses-library            android:name="org.apache.http.legacy"            android:required="false" />
    </application>

</manifest>

Enjoy coding.if you get any problem comment in the comment section.






Comments

Popular posts from this blog

Insert data into database using Android,php & Mysql

Random password Generator In PHP

How to select data from mysql database using PHP