Android ListView - With RatingBar, Images and Text


Android ListView - With RatingBar, Images and Text Tutorial and Example.

Lets see how to work with a Custom ListView with RatingBar.

Moreover, the ListView shall hava images and text. We shall be using five stars in our ratingbar, and set their values programmatically in java code.

When the user clicks a single ListView viewitem, we display the value of the associated card.Our viewitems shall be cardviews. We are using SimpleRatingBar library. We shall set the ratingbar properties in xml code, e.g number of stars, step size, star size etc.

STEP 1 : Build.Gradle.
  • Add Dependency for CardView and SimpleRatingBar.
  • Then sync.SimpleRatingBar is fetched from online.

 

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.iarcuschin:simpleratingbar:0.1.3'

}
STEP 2 : Add Images
  • Just add images to your drawable folder.Our recyclerview shall be displaying images.
STEP 3 : ActivityMain.xml
  • This is a layout that gets generated by android studio in case you chose Basic Activity as template during project creation.

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.listviewratingbar.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.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"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
STEP 4 : ContentMain.xml
  •  Add the ListView here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.listviewratingbar.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</RelativeLayout>
STEP 5 : Model.xml
  • Our model layout.
  • We add imageview,textview and ratingbar.
  • Set the ratingbar properties like number of stars and step size here.Also the colors.

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="10dp"
    card_view:cardElevation="5dp"
    android:layout_height="300dp">

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

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="220dp"
            android:id="@+id/spacecraftImage"
            android:padding="5dp"
            android:src="@drawable/enterprise" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="5dp"
                android:layout_weight="1" />

            <com.iarcuschin.simpleratingbar.SimpleRatingBar
                android:id="@+id/ratingBarID"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                app:srb_starSize="40dp"
                app:srb_numberOfStars="5"
                app:srb_rating="3"
                app:srb_stepSize="1"
                app:srb_borderColor="@color/colorPrimaryDark"
                app:srb_fillColor="@color/colorPrimary"
                android:layout_alignBottom="@+id/spacecraftImage"
                android:layout_alignParentRight="true"
                />
        </LinearLayout>

    </LinearLayout>
</android.support.v7.widget.CardView>
STEP 6  : Spaceship class
  • This is our data object class.

 

package com.tutorials.hp.listviewratingbar.mData;

public class Spaceship {

    /*
    SPACESHIP PROPERTIES
     */
    private int rating;
    private String name;
    private int image;

    /*
    GETTERS AND SETTERTS
     */
    public float getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}
STEP 7 : SpaceshipCollection class
  • Exposes a static method that acts as our data source.

 

package com.tutorials.hp.listviewratingbar.mData;

import com.tutorials.hp.listviewratingbar.R;

import java.util.ArrayList;

public class SpaceshipsCollection{

    /*
    1.CREATE SPACESHIP OBJECTS AND ASSIGN THEM PROPERTIES
    2.RETURN LIST OF THESE SPACESHIP OBJECTS
     */

    public static ArrayList<Spaceship> getSpaceships()
    {
        ArrayList<Spaceship> spaceships=new ArrayList<>();

        Spaceship s=new Spaceship();
        s.setName("Spitzer");
        s.setRating(4);
        s.setImage(R.drawable.spitzer);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Enterpise");
        s.setRating(3);
        s.setImage(R.drawable.enterprise);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Voyager");
        s.setRating(5);
        s.setImage(R.drawable.voyager);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Opportunity");
        s.setRating(3);
        s.setImage(R.drawable.opportunity);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Pioneer");
        s.setRating(2);
        s.setImage(R.drawable.pioneer);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("WMAP");
        s.setRating(4);
        s.setImage(R.drawable.wmap);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Rosetter");
        s.setRating(1);
        s.setImage(R.drawable.rosetta);
        spaceships.add(s);

        s=new Spaceship();
        s.setName("Hubble");
        s.setRating(5);
        s.setImage(R.drawable.hubble);
        spaceships.add(s);

        return spaceships;
    }

}
STEP 8  : CustomAdapter class
  • Our adapter class.
  • Binds our dataset to our listview.
  • Inflates the model layout to viewitem.

 

package com.tutorials.hp.listviewratingbar.mAdapterView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.tutorials.hp.listviewratingbar.R;
import com.tutorials.hp.listviewratingbar.mData.Spaceship;

import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {

    private ArrayList<Spaceship> spaceships;
    private Context c;

    public CustomAdapter(Context c,ArrayList<Spaceship> spaceships) {
        this.spaceships = spaceships;
        this.c = c;
    }

    @Override
    public int getCount() {
        return spaceships.size();
    }

    @Override
    public Object getItem(int i) {
        return spaceships.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    /*
    INFLATE XML LAYOUT TO VIEW
     */
    @Override
    public View getView(int pos, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
        }

        TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
        ImageView img= (ImageView) view.findViewById(R.id.spacecraftImage);
        SimpleRatingBar ratingBar= (SimpleRatingBar) view.findViewById(R.id.ratingBarID);

        final Spaceship s= (Spaceship) this.getItem(pos);

        nameTxt.setText(s.getName());
        ratingBar.setRating(s.getRating());
        img.setImageResource(s.getImage());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(c, s.getName()+ " Rating : "+String.valueOf(s.getRating()), Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}
STEP 9 : MainActivity
  • Initialize ListView, set its adapter.

 

package com.tutorials.hp.listviewratingbar;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;

import com.tutorials.hp.listviewratingbar.mAdapterView.CustomAdapter;
import com.tutorials.hp.listviewratingbar.mData.SpaceshipsCollection;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ListView lv= (ListView) findViewById(R.id.lv);
        lv.setAdapter(new CustomAdapter(this, SpaceshipsCollection.getSpaceships()));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

}
How To Run
  1. Download the project.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.
More Resources
Resource Link
GitHub Browse Browse
GitHub Download Link Download

Good day.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post