Android Material List - With Texts,Images and Action Buttons

October 24, 2017 Oclemy Android Material List 7 minutes, 16 seconds

Android Material List Example - Title,Description, Images and action buttons In this class,we see how to work with Material List, an Android library aimed to get the beautiful CardViews that Google shows at its official design specifications.

We are going to fill it with an array of objects. In this example we use Galaxy object. Each galaxy has a title, a description, an image and two action buttons. We then see how to handle the click events for these CardView action buttons, hence shoing a toast message. This library is built on top of RecyclerView, hence its very flexible.

It's very easy to create a list of cards, you don't need any boilerplate adapter code. You can just instantiate a Card object and using builder style append a title,subtitle,description,image etc.

Screenshot

  • Here's the screenshot of the project.

Android Material List Button One Click:

Android Material List Button One Click

Android Material List Button Two Click:

Android Material List Button Two Click

Android Material List : Project Structure.

Android Material List Example Project Structure

Common Questions this example explores

  • Android Material List Example.
  • Android Material List with text, images and action buttons.
  • CardViews with action buttons.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • Genymotion Emulator
  • Language : Java
  • Topic : Material List, Material ListView, RecyclerView, Cards

Libaries Used

Source Code

Lets jump directly to the source code.

Build.Gradle App Level

  • Our app level build.gradle file.
  • We specify compilesdk,minimum sdk,target sdk and dependencies.
  • Note that the minimum sdk for this project isn't that strict,it is much lower than that specified below.
  • We also add dependencies using 'compile' statement.
  • Our activity shall derive from the appCompatActivity to make it target earlier android versions.
  • We also specify constraint-library as our activity_main.xml will use it as the root tag.
  • Finally we add the com.github.dexafree:materiallist which which is a third party library built on top of Recycleriew. We'll use it to create amazing Cards.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.tutorials.hp.materialarray"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'

    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.github.dexafree:materiallist:3.2.1'

}

Galaxy.java

  • Our data object class
  • Represents a single galaxy with name,description and image.
  • Takes in property values via Constructor.
  • Exposes them via getter methods.
package com.tutorials.hp.materialarray;

public class Galaxy {
    private String name,description;
    private int image;

    public Galaxy(String name, String description, int image) {
        this.name = name;
        this.description = description;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public int getImage() {
        return image;
    }

}

MainActivity.java

  • Our MainActivity.
  • Derives from AppCompatActivity, which is a Base class for activities that use the support library action bar features.
  • Inflates ActivityMain.xml layout using setContentView() method.
  • Views shown include a GridView.
  • Methods: onCreate(),initialViews(),createCard(),getData().
  • The purpose of this activity is to create an Array of Cards with title,description,images and action button and add them to material list.
package com.tutorials.hp.materialarray;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
import com.dexafree.materialList.card.Card;
import com.dexafree.materialList.card.CardProvider;
import com.dexafree.materialList.card.OnActionClickListener;
import com.dexafree.materialList.card.action.TextViewAction;
import com.dexafree.materialList.view.MaterialListView;
import com.squareup.picasso.RequestCreator;

public class MainActivity extends AppCompatActivity {

    MaterialListView materialListView;

    /*
    - When activity is created
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.initializeViews();
        this.bindData();
    }

    /*
    - Initialize Material ListView.
     */
    private void initializeViews()
    {
        materialListView= (MaterialListView) findViewById(R.id.material_listview);
    }

    /*
    - Bind data to Material ListView.
     */
    private void bindData() {
        for (Galaxy g : getData()) {
            this.createCard(g);
        }
    }
    /*
    - Create a CardView with title,description, image and image.
     */
    private void createCard(final Galaxy g){
        Card card = new Card.Builder(this)
                .withProvider(new CardProvider())
                .setLayout(R.layout.material_basic_image_buttons_card_layout)
                .setTitle(g.getName())
                .setTitleGravity(Gravity.END)
                .setDescription(g.getDescription())
                .setDescriptionGravity(Gravity.END)
                .setDrawable(g.getImage())
                .setDrawableConfiguration(new CardProvider.OnImageConfigListener() {
                    @Override
                    public void onImageConfigure(@NonNull RequestCreator requestCreator) {
                        //requestCreator.fit();
                        requestCreator.resize(121,121);
                    }
                })
                .addAction(R.id.left_text_button, new TextViewAction(this)
                        .setText("Button 1")
                        .setTextResourceColor(R.color.colorAccent)
                        .setListener(new OnActionClickListener() {
                            @Override
                            public void onActionClicked(View view, Card card) {
                                Toast.makeText(getApplicationContext(), "Right button on card " +g.getName(), Toast.LENGTH_SHORT).show();
                            }
                        }))
                .addAction(R.id.right_text_button, new TextViewAction(this)
                        .setText("Button 2")
                        .setTextResourceColor(R.color.orange_button)
                        .setListener(new OnActionClickListener() {
                            @Override
                            public void onActionClicked(View view, Card card) {
                                Toast.makeText(getApplication(), "Right button on card " + card.getProvider().getDescription(), Toast.LENGTH_SHORT).show();
                            }
                        }))
                .endConfig()
                .build();

        // Add Card to ListView
        materialListView.getAdapter().add(card);
    }

    /*
    - Our data source
     */
    private Galaxy[] getData()
    {
        Galaxy[] galaxies = new Galaxy[10];

        Galaxy g=new Galaxy("Whirlpool",
                "The Whirlpool Galaxy, also known as Messier 51a, M51a, and NGC 5194, is an interacting grand-design spiral galaxy with a Seyfert 2 active galactic nucleus in the constellation Canes Venatici.",
                R.drawable.whirlpool);
        galaxies[0]=g;

        g=new Galaxy("Triangulumn",
                "The Triangulum Galaxy is a spiral galaxy approximately 3 million light-years from Earth in the constellation Triangulum",
                R.drawable.triangulum);
        galaxies[1]=g;

        g=new Galaxy("Milky Way",
                "The Milky Way is the galaxy that contains our Solar System." +
                " The descriptive milky is derived from the appearance from Earth of the galaxy – a band of light seen in the night sky formed from stars",
                R.drawable.milkyway);
        galaxies[2]=g;

        g=new Galaxy("Andromeda",
                "The Andromeda Galaxy, also known as Messier 31, M31, or NGC 224, is a spiral galaxy approximately 780 kiloparsecs from Earth. It is the nearest major galaxy to the Milky Way and was often referred to as the Great Andromeda Nebula in older texts.",
                R.drawable.andromeda);
        galaxies[3]=g;

        g=new Galaxy("StarBust",
                "A starburst galaxy is a galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average rate of star formation in the galaxy or the star formation rate observed in most other galaxies. ",
                R.drawable.starbust);
        galaxies[4]=g;

        g=new Galaxy("Messier 81",
                "Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth, large size and active galactic nucleus, Messier 81 has been studied extensively by professional astronomers.",
                R.drawable.messier81);
        galaxies[5]=g;

        g=new Galaxy("Sombrero",
                "Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo located 31 million light-years from Earth. The galaxy has a diameter of approximately 50,000 light-years, 30% the size of the Milky Way.",
                R.drawable.sombrero);
        galaxies[6]=g;

        g=new Galaxy("Pinwheel",
                "The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa Major. ",
                R.drawable.pinwheel);
        galaxies[7]=g;

        g=new Galaxy("Canis Majos Overdensity",
                "The Canis Major Dwarf Galaxy or Canis Major Overdensity is a disputed dwarf irregular galaxy in the Local Group, located in the same part of the sky as the constellation Canis Major. ",
                R.drawable.canismajoroverdensity);
        galaxies[8]=g;

        g=new Galaxy("Cosmos Redshift",
                "Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter galaxy, in the constellation Sextans, about 12.9 billion light travel distance years from Earth, reported to contain the first stars —formed ",
                R.drawable.cosmosredshift);
        galaxies[9]=g;

        return galaxies;
    }
}

ActivityMain.xml

  • ActivityMain.xml layout.
  • Our MainActivity Layout.
  • Root tag is ConstraintLayout ViewGroup.
  • We then add MaterialListView, which is a child of RecyclerView.
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.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="com.tutorials.hp.materialarray.MainActivity">

    <com.dexafree.materialList.view.MaterialListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/material_listview"/>

</android.support.constraint.ConstraintLayout>

Video/Preview

  • We have a YouTube channel with almost a thousand tutorials, this one below being one of them.

https://www.youtube.com/watch?v=Mcr4hmWQcQ8

Download

  • You can Download the full Project below. Source code is well commented.

Download

How To Run

  1. Download the project above.
  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

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.

Comments