ViewPager2 | View.ClickListener未调用

时间:2019-04-27 12:06:05

标签: android android-viewpager2

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

我的Actvity课程:

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>

任何假设或解决方法?

1 个答案:

答案 0 :(得分:0)

我找到了决定! 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)
            }
        }
    }
}