android - 适配器引用生成的类 (android-sunflower)
问题描述
我正在查看 Google 的一个名为SunflowerKotlin
的示例应用程序,我用它来了解/是如何工作的。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
这意味着ListItemPlantBinding
为list_item_plant.xml生成
数据绑定由
dataBinding {
enabled = true
}
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>
有关如何启用导航,请参阅导航架构组件文档
推荐阅读
- haskell - 使用 mfix 避免无限递归
- java - 如何从不同的数据库中获取映射的实体?
- python - Telethon 在按钮之后写消息/开始聊天 - 机器人在 /start 之前发送消息
- javascript - 在 c# (Unity) 中解析 JSON 文件
- xcode - 在 Appstore 上将版本设置为仅限 iPad
- php - 从 Laravel 的下拉菜单中获取数据
- next.js - NextJS 拆分块缓存在开发模式下不起作用
- visual-studio-code - 如何使用我的自定义字符串修改 VSCode 中的第 3 行(n)和每个 n+6(如 9、15、24 等)?
- c++ - 指针和整数的模棱两可的重载?
- android - 类中的空共享首选项