Welcome to ZaiZheLe Developer Zone-Open, Learning and Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

android studio - Kotlin AddOnPageChangeListener not working

I wanted to connect a viewPager with an adapter (like this: viewPager.addOnPageChangeListener()), but the letters of the pageChangeListener just turn red like it wasn't a valid code...What am I doing wrong?? Heres a screenshot: [1]: https://i.stack.imgur.com/IOYJY.png

Context: I'm currently working on a game with a few fragments where you can choose your game cards. I need the pageChangeListener to change the pictures of them cards. Maybe there could be another way to do this but i don't know how...

package com.suffv1

import android.os.Bundle
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import com.example.suff_02.Adapter2
import com.example.suff_02.R
import com.example.suff_02.kartenmodell

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(){

    private lateinit var actionbar: ActionBar

    private lateinit var liste: ArrayList<kartenmodell>
    private lateinit var myAdapter: Adapter2

    override fun onCreate(savedInstanceState: Bundle?) {

        actionbar = this.supportActionBar!!


        viewpager2.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                val title = liste[position].KartenImage
                actionbar.title = title



    private fun loadCards() {
        liste = ArrayList()


        myAdapter = Adapter2(this, liste)

        viewpager2.adapter = myAdapter

        viewpager2.setPadding(100, 0, 100, 0)


Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looks like you are using ViewPager2 not the original Viewpager and Viewpager2 does not have Page Change Listeners it instead has Page Change Callbacks

So you are using the wrong method to get notified when a pages is changed.

Instead do something like

var myPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    Toast.makeText([email protected], "Selected position: ${position}", 


Though architecturally a lot of times it is bad form to use a OnPageChangeCallback as you are likely breaking the encapsulation idea of the Fragment and it can be better to use the lifecycle state change to Resumed of the Fragment to do things when a page(Fragment) is selected. e.g. put the code in the Fragments onResume method.

Though in this case of setting the actionbar title it is probably ok architecturally to use a OnPageChangeCallback

Welcome to ZaiZheLe Developer Zone-Open, Learning and Share

548k questions

547k answers


37.7k users