我正在看谷歌的一个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.PlantListFragmentDirectionsimport com.google.samples.apps.sunflower.databinding.ListItemPlantBinding他们不在项目结构中。这是怎么回事?
发布于 2018-08-16 23:24:12
这是两种不同的生成类。它们是在构建过程中自动生成的(以及在使用Android时动态生成的)。命名遵循在.xml资源文件中定义的名称,其后缀与其组件对应。
1. ListItemPlantBinding
ListItemPlantBinding是为数据绑定生成的类,请参阅生成的数据绑定文档。
上面的布局文件名是activity_main.xml,因此相应的生成类是ActivityMainBinding。
这意味着ListItemPlantBinding是为plant.xml生成的。
启用数据绑定。
dataBinding {
enabled = true
}2. PlantListFragmentDirections
导航体系结构组件文档指出了第二个答案。
作为动作起源的目的地的一个类,附加了“说明”一词。
因此,PlantListFragmentDirections起源于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>
有关如何启用导航,请参阅导航体系结构组件文档
https://stackoverflow.com/questions/51884303
复制相似问题