如何在 OnClick 中更改 activity 中适配器位置的值?

How to change the value of the adapter position in the activity in an OnClick?

在我的适配器中有一个ViewPager我有位置。我想做的是通过在 activity 中按 Button 将位置加 1,但我无法从 activity 访问该位置。我该怎么做?

适配器:

class MyAdapter(var context: Context,private var myList: List<MyModel>) : PagerAdapter() {
        
    override fun getCount(): Int {
        return myList.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View?)
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {

        var view: View = LayoutInflater.from(context).inflate(R.layout.layout_item,container,false)
        var img: ImageView = view.findViewById(R.id.imgView)
        val listPos= myList[position]

        container.addView(view)
        return view

    }      
}

Activity:

class MyActivity : AppCompatActivity() {

    private var myAdapter: MyAdapter? = null
    private val myList = ArrayList<MyModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity_layout)
        myAdapter = MyAdapter(this,myList)
        myViewPager.adapter = myAdapter
        myList.add("Name",R.drawable.img1)
        myList.add("Name2",R.drawable.img2)
        myList.add("Name3",R.drawable.img3)

        myButtonPlus.setOnClickListener{
            //Here I want to +1 the position for every click
        }
        myButtonMinus.setOnClickListener{
            //Here I want to -1 the position for every click
        }
    }
}

如果您想增加和减少您的 ViewPager 头寸,您应该使用 setCurrentItem 功能。

尝试像这样更改您的代码:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.my_activity_layout)
    myAdapter = MyAdapter(this,myList)
    myViewPager.adapter = myAdapter
    myList.add("Name",R.drawable.img1)
    myList.add("Name2",R.drawable.img2)
    myList.add("Name3",R.drawable.img3)

    myButtonPlus.setOnClickListener{
        //Here I want to +1 the position for every click
        val currentPage = myAdapter?.currentItem ?: 0
        val maxPage = myAdapter?.childCount ?: 0

        if (currentPage < maxPage) {
            myAdapter?.currentItem = currentPage + 1
        }
    }
    myButtonMinus.setOnClickListener{
        //Here I want to -1 the position for every click
        val currentPage = myAdapter?.currentItem ?: 0

        if (currentPage > 0) {
            myAdapter?.currentItem = currentPage - 1
        }
    }
}