我正在查看Google的一个名为Sunflower的Kotlin
示例应用程序,我正在使用该应用程序来了解Kotlin
/Android 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()
}
}
}
}
我感到困惑的是它在哪里变得PlantListFragmentDirections
和ListItemPlantBinding
?当我跳转到这些类的定义时,它们位于自动生成的build
文件夹中。当我看进口时
import com.google.samples.apps.sunflower.PlantListFragmentDirections
import com.google.samples.apps.sunflower.databinding.ListItemPlantBinding
它们不在项目结构中。这是如何工作的?
这是两种不同类型的生成类。它们是在构建过程中自动生成的(使用Android Studio时会动态生成(。命名遵循.xml资源文件中定义的名称,并带有与其组件对应的后缀。
1.ListItemPlantBinding
ListItemPlantBinding
是为数据绑定生成的类,请参阅生成的数据绑定文档
上面的布局文件名是activity_main.xml所以相应的生成类是ActivityMainBinding
这意味着为list_item_plant.xml生成ListItemPlantBinding
数据绑定由
dataBinding {
enabled = true
}
In build.gradle
2.PlantListFragmentDirections
导航体系结构组件文档指向第二个答案。
操作发起的目标的类,后附加单词"方向"。
因此,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>
请注意带有随附<action>
的<fragment>
元素
有关如何启用导航,请参阅导航体系结构组件文档