问题
I use new android widget ViewPager2 version 1.0.0-alpha03 and when I set click listener on it method onClick() not called.
My Actvity class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction()
.add(R.id.fragmentContent, SecondFragment.newInstance(), SecondFragment.TAG)
.addToBackStack(SecondFragment.TAG)
.commit()
}
}
My Fragment:
class SecondFragment : Fragment() {
companion object {
val TAG = SecondFragment::class.java.canonicalName
fun newInstance(): SecondFragment = SecondFragment()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewPager2.setOnClickListener {
Log.d("logi", "click : ")
}
}
}
My layout xml file:
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Any assumption or workaround?
回答1:
I found a solution! ViewPager2
contains RecyclerView
and we must work with it as RecyclerView
. I created RecyclerView.Adapter and set the ClickListener on itemView into the constructor RecyclerView.ViewHolder and VOILA!!!
in Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewPager2.adapter = ViewPager2Adapter {
Log.d("logi", "clicked at : $it")
}
}
RecyclerView adapter:
class ViewPager2Adapter(private val itemClickListener: (Int) -> (Unit)) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val items = mutableListOf<Any>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
ItemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false))
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
// bind your items
}
private inner class ItemViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
Log.d("logi", "Click!") // WORKS!!!
itemClickListener(adapterPosition)
}
}
}
}
来源:https://stackoverflow.com/questions/55880388/viewpager2-view-clicklistener-not-called