Firstly, we will start by creating a new empty activity project.
Now, we will add the affirmation strings to the app in the strings.xml file.
<resources> <string name="app_name">Affirmations</string> <string name="affirmation1">I am strong.</string> <string name="affirmation2">I believe in myself.</string></resources>
Now that we have added string resources, we can reference them in our code as R.string.affirmation1 or R.string.affirmation2.
Moving forward we will create a new package named model in the affirmation app. Under that create a class Affirmation.kt
package com.example.affirmations.model
data class Affirmation(val stringResourceId: Int)
Added a val integer parameter stringResourceId to the constructor of the Affirmation class.
Now we will create a class to be a data source, and under that, we will create a function called loadAffirmation() and will add the Affirmation objects to the list.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
// Initialize data. val myDataset = Datasource().loadAffirmations()
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view) recyclerView.adapter = ItemAdapter(this, myDataset)
// Use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView recyclerView.setHasFixedSize(true) } }
Then we will run the app and it will look like this:
Affirmations
Today I Learned:
RecyclerView widget helps us to display a list of data.
RecyclerView uses the adapter pattern to adapt and display the data.
ViewHolder creates and holds the views for RecyclerView.
RecyclerView comes with built-in LayoutManagers. RecyclerView delegates how items are laid out to LayoutManagers.