Actions

Kotlin Recycler Views

From zen2

For recycler we will NOt have setOnItemClickListener as below:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        adapter = CategoryAdapter(this, DataService.categories)
        categoryListView.adapter = adapter
        categoryListView.setOnItemClickListener { parent, view, position, id ->
            val category = DataService.categories[position]
            Toast.makeText(this, "You clicked on the ${category.title}", Toast.LENGTH_SHORT).show()
        }
    }

Instead:

We need to add the recycler support library:

  • Open build.gradle (Module: app)
  • In dependencies create a space after implementations, press alt-enter, add library dependency, then choose the one with recyclerview. This may ass it at the bottom, you can move it up. It should be something like this:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

You will then need to Sync Now (top right) to resync gradle.

Now, in your layout xml file you swap the ListView for recycleview. eg Replace

<ListView
...

with:

<android.support.v7.widget.RecyclerView
...