首页 > 解决方案 > 适配器引用生成的类 (android-sunflower)

问题描述

我正在查看 Google 的一个名为SunflowerKotlin的示例应用程序,我用它来了解/是如何工作的。KotlinAndroid Jetpack

PlantAdapter是以下代码:

/**
 * Adapter for the [RecyclerView] in [PlantListFragment].
 */
class PlantAdapter : ListAdapter<Plant, PlantAdapter.ViewHolder>(PlantDiffCallback()) {

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val plant = getItem(position)
        holder.apply {
            bind(createOnClickListener(plant.plantId), plant)
            itemView.tag = plant
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(ListItemPlantBinding.inflate(
                LayoutInflater.from(parent.context), parent, false))
    }

    private fun createOnClickListener(plantId: String): View.OnClickListener {
        return View.OnClickListener {
            val direction = PlantListFragmentDirections.ActionPlantListFragmentToPlantDetailFragment(plantId)
            it.findNavController().navigate(direction)
        }
    }

    class ViewHolder(
        private val binding: ListItemPlantBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(listener: View.OnClickListener, item: Plant) {
            binding.apply {
                clickListener = listener
                plant = item
                executePendingBindings()
            }
        }
    }
}

我感到困惑的是它在哪里得到PlantListFragmentDirectionsListItemPlantBinding?当我跳转到这些类的定义时,它们位于build自动生成的文件夹中。当我查看进口商品时

它们不在项目结构中。这是如何运作的?

标签: androidkotlinandroid-jetpack

解决方案


这是两种不同类型的生成类。它们是在构建过程中自动生成的(在使用 Android Studio 时是动态生成的)。命名遵循 .xml 资源文件中定义的名称,并带有与其组件对应的后缀。

1. ListItemPlantBinding

ListItemPlantBinding是为数据绑定生成的类,请参阅生成的数据绑定文档

上面的布局文件名是activity_main.xml,所以对应生成的类是ActivityMainBinding

这意味着ListItemPlantBindinglist_item_plant.xml生成

数据绑定由

dataBinding {
     enabled = true
}

build.gradle

2. PlantListFragmentDirections

导航架构组件文档指向第二个答案。

动作起源的目的地类,附加单词“Directions”。

因此PlantListFragmentDirections源自nav_garden.xml

 <fragment
    android:id="@+id/plant_list_fragment"
    android:name="com.google.samples.apps.sunflower.PlantListFragment"
    android:label="@string/plant_list_title"
    tools:layout="@layout/fragment_plant_list">

    <action
        android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"
        app:destination="@id/plant_detail_fragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_right" />
</fragment>

注意<fragment>带有封闭的元素<action>

有关如何启用导航,请参阅导航架构组件文档


推荐阅读