11

我使用新的 android 小部件 ViewPager2 版本 1.0.0-alpha03 并且当我在其上设置点击侦听器时,未调用 onClick() 方法。

我的活动课:

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()
    }
}

我的片段:

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 : ")
        }
    }
}

我的布局 xml 文件:

<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>

任何假设或解决方法?

4

1 回答 1

12

我找到了解决办法!ViewPager2包含RecyclerView,我们必须将其作为RecyclerView. 我创建了 RecyclerView.Adapter 并将 itemView 上的 ClickListener 设置为构造函数 RecyclerView.ViewHolder 和 VOILA !!!

在片段中:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewPager2.adapter = ViewPager2Adapter {
            Log.d("logi", "clicked at : $it")
        }
    }

RecyclerView 适配器:

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)
            }
        }
    }
}
于 2019-04-27T14:40:05.373 回答