我有一个ViewPager2,显示了3种具有不同内容的不同布局。一切工作正常,但我想在活动中访问这些布局的视图,而不是从适配器固定器访问。
这是我的适配器的支架:-
class ServiceRequestViewHolder( _itemView: View, _context: Context) : RecyclerView.ViewHolder(_itemView) {
// context
private val cxt: Context = _context
// view
private var v: View = _itemView
/**
* this fun is called from the onBindViewHolder of the adapter and
* handles the switching of the layouts
*
* @param position
*/
fun navigation(
position: Int
): View? {
val inflater: LayoutInflater = LayoutInflater.from(cxt)
val parentContainer = v.findViewById<LinearLayout>(R.id.viewContainer)
when (position) {
0 -> {
v =
inflater.inflate(R.layout.layout_one, null)
// i don't want to do this
val button = v.findViewById<Button>(R.id.button_in_layout_one)
button.setOnClickListener {
// handle button click event
}
}
1 -> {
v =
inflater.inflate(R.layout.layout_two, null)
}
2 -> {
v =
inflater.inflate(R.layout.layout_three, null)
}
} // when loop
parentContainer.addView(v)
return v
}
}
所以我在Activity类中尝试了类似的东西;
private var pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
}
// in onCreate
viewPager2.registerOnPageChangeCallback(pageChangeCallback)
是否可以访问onPageSelected的position参数并使用它来获取当前视图? 任何帮助表示赞赏。谢谢