AndroidX RecycleView in KOTLIN

AndroidX is the Android Extension library which is very new and exited Support in android library. All Android Developer using AndroidX supports for newer OS features. This should help you to integrate recycle view.

AndroidX RecycleView in KOTLIN

Androidx  Recycleview (listing)

Download App from here :  AndroidXRecycleView

 

To convert android aproject into androidx we have to follow below steps.

1. Need to add below line in gradle.properties

android.useAndroidX=true

android.enableJetifier=true

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

android.useAndroidX=true
android.enableJetifier=true

2. Add androidx dependencies in gradle file.

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:design:28.0.0'

    // app compact
    implementation "androidx.appcompat:appcompat:1.1.0-alpha04"

    // constraint layout
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    // recycle view
    implementation 'androidx.recyclerview:recyclerview:1.1.0-beta01'
    // glide

    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

}

 

 Creating a sample Project in android studio

 

1. Create a sample project from android studio. to create a sample project please go to below steps:

File  -> New -> New Project --> A popup will come then select a empty activity.

2. Open project app -> res -> change resource values file like strings, color, dimens.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
    <color name="colorGrey">#A6A6A6</color>
    <color name="colorBackTransparent_40">#A4FFFFFF</color>
</resources>

strings.xml

<resources>
    <string name="app_name">AndroidXRecycleView</string>
    <string name="action_settings">Settings</string>
</resources>

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

 

 

3.  Open application app project gradle file and  add implement all dependencies :

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:design:28.0.0'

    // app compact
    implementation "androidx.appcompat:appcompat:1.1.0-alpha04"

    // constraint layout
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    // recycle view
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha04'


    // glide

    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'


    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

 

4. To show item in list so here for example i will going to display a single item BOOK. The BOOK (Model) class with some  attributes is defined like this.

package datanapps.androidxrecycleview

class Book {
    var bookTitle: String? = null
    var authorName: String? = null
    var bookImage: String? = null
    var publishedYear: Int = 0
}

 

5.  To display a layout in Recycleview, we create a layout for adapter which will inflate in adapter class.

layout_book_list.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="250dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">


    <ImageView
        android:id="@+id/layout_book_list_book_cover"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:contentDescription="@string/app_name"
        app:layout_constraintTop_toTopOf="parent"
       android:background="@color/colorGrey"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="@color/colorBackTransparent_40"
        >
        <TextView
            android:id="@+id/layout_book_list_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:textSize="20sp"
            app:layout_constraintTop_toTopOf="parent"
            android:textColor="@color/colorAccent"
            tools:text="title" />

        <TextView
            android:id="@+id/layout_book_list_author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="16dp"
            tools:text="Author"
           android:layout_below="@+id/layout_book_list_title"
            android:textColor="@android:color/black"
           />

        <TextView
            android:id="@+id/layout_book_list_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="16dp"
            tools:text="year"
            android:paddingEnd="5dp"
            android:layout_alignParentEnd="true"
            android:layout_below="@+id/layout_book_list_title"
            android:textColor="@android:color/black"
            />

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

6.  Now going to create a adapter for recycle view and here we will use above created layout and model.  

BooksAdapter.class

package datanapps.androidxrecycleview

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

import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions

import androidx.recyclerview.widget.RecyclerView

class BooksAdapter(private val context: Context, private val moviesList: List<Book>) : RecyclerView.Adapter<BooksAdapter.UserViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.layout_book_list, parent, false)

        return UserViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        val book = moviesList[position]
        holder.bookName.text = book.bookTitle
        holder.bookAuthor.text = book.authorName
        holder.publishedYear.text = book.publishedYear.toString()


        Glide
                .with(context)
                .load(book.bookImage)
                .apply(RequestOptions().fitCenter())
                .into(holder.imageCover)
    }

    override fun getItemCount(): Int {
        return moviesList.size
    }

    inner class UserViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var bookName: TextView
        var bookAuthor: TextView
        var imageCover: ImageView
        var publishedYear: TextView
        init {
            bookName = view.findViewById(R.id.layout_book_list_title)
            bookAuthor = view.findViewById(R.id.layout_book_list_author)
            imageCover = view.findViewById(R.id.layout_book_list_book_cover)
            publishedYear = view.findViewById(R.id.layout_book_list_year)
        }
    }
}

7. Now open res -> layout -> activity.main.xml  and replace with below code.

activity.main.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=".MainActivity">


    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:layout_constraintTop_toTopOf="parent">

        <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/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycle_view_book"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:layout_marginTop="?android:attr/actionBarSize"
        app:layout_constraintTop_toBottomOf="@+id/appbar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="@+id/appbar"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_input_add"
        app:fabCustomSize="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

8.  Open Main activity and write this code.   

MainActivity.java

package datanapps.androidxrecycleview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import java.util.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // set tool bar
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        // set floating action
        val fab = findViewById<FloatingActionButton>(R.id.fab_bar)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }

        // set recycle view
        setRecycleViewList()
    }

    private fun setRecycleViewList() {
        val recyclerView = findViewById<RecyclerView>(R.id.recycle_view_book)
        val mAdapter = BooksAdapter(this@MainActivity, bookList)
        val mLayoutManager = LinearLayoutManager(applicationContext)
        recyclerView.layoutManager = mLayoutManager
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = mAdapter
    }


    private//---------------------------------------//
    val bookList: List<Book>
        get() {

            val bookList = ArrayList<Book>()

            var book = Book()
            book.bookTitle = "History-books-for-Kids"
            book.authorName = "unknown"
            book.bookImage = "https://tessajwooldridge.files.wordpress.com/2016/11/history-books-for-kids_tea-and-christmas-sugar_5.jpg"
            book.publishedYear = 2000
            bookList.add(book)

            book = Book()
            book.bookTitle = "The Girl without a name"
            book.authorName = "aaa"
            book.bookImage = "https://static1.squarespace.com/static/5746d6f1b654f905c35b5158/t/574f92014c2f85c0e9423612/1466204180094/"
            book.publishedYear = 1995
            bookList.add(book)

            book = Book()
            book.bookTitle = "Classic-Childrens-Books"
            book.authorName = "unknown"
            book.bookImage = "https://dygtyjqp7pi0m.cloudfront.net/i/5736/8633103_1.jpg?v=8CE71410914F540"
            book.publishedYear = 1995
            bookList.add(book)

            book = Book()
            book.bookTitle = "4 Haunted Man"
            book.authorName = "unknown"
            book.bookImage = "https://www.tfwalsh.com/wp-content/uploads/2018/05/Banner-3.jpg"
            book.publishedYear = 2005
            bookList.add(book)

            book = Book()
            book.bookTitle = "The Girl without a name"
            book.authorName = "aaa"
            book.bookImage = "https://static1.squarespace.com/static/5746d6f1b654f905c35b5158/t/574f92014c2f85c0e9423612/1466204180094/"
            book.publishedYear = 1995
            bookList.add(book)



            book = Book()
            book.bookTitle = "Dark Movie"
            book.authorName = "John Deo"
            book.bookImage = "https://bluefx.net/wp-content/uploads/2014/06/dark-movie-titles-after-effects-template.jpg"
            book.publishedYear = 1999
            bookList.add(book)

            book = Book()
            book.bookTitle = "Latinx-Must"
            book.authorName = "unknown"
            book.bookImage = "https://d4804za1f1gw.cloudfront.net/wp-content/uploads/sites/22/2018/08/21114706/Latinx-Must-Reads-Banner.png"
            book.publishedYear = 2000
            bookList.add(book)

            book = Book()
            book.bookTitle = "My Story"
            book.authorName = "John Deo"
            book.bookImage = "https://0.s3.envato.com/files/183895378/preview%20image_590x300.jpg"
            book.publishedYear = 1997
            bookList.add(book)

            book = Book()
            book.bookTitle = "White Dragon"
            book.authorName = "unknown"
            book.bookImage = "https://arthive.com/res/media/img/oy800/work/e58/183471.jpg"
            book.publishedYear = 2005
            bookList.add(book)


            book = Book()
            book.bookTitle = "XuGkeTK"
            book.authorName = "unknown"
            book.bookImage = "http://i.imgur.com/XuGkeTK.jpg"
            book.publishedYear = 2009
            bookList.add(book)


            book = Book()
            book.bookTitle = "XuGkeTK"
            book.authorName = "unknown"
            book.bookImage = "https://ksr-ugc.imgix.net/assets/014/535/121/fb5e7a5dcdd5fbc02a27290508feb0ee_original.jpg?ixlib=rb-1.1.0&crop=faces&w=1552&h=873&fit=crop&v=1479972288&auto=format&frame=1&q=92&s=ffaab00f1731b16ba4626b066ac5177e"
            book.publishedYear = 2009
            bookList.add(book)


            book = Book()
            book.bookTitle = "My Story"
            book.authorName = "John Deo"
            book.bookImage = "https://0.s3.envato.com/files/183895378/preview%20image_590x300.jpg"
            book.publishedYear = 1996
            bookList.add(book)

            return bookList
        }
}

Please download project and sample here.    AndroidX RecycleView

-----------------------------------------------

please click LIKE button and SHARE to help others find it!

Please suggest ideas for my next blog in comment section.

Thank you so much, Have a great day !

 


Click Here To See More

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0