以下代码来自项目 https://github.com/mycwcgr/camera/tree/master/CameraXBasic
该项目使用最新的导航框架,我发现有一些保留的类名,如CameraFragmentDirections,GalleryFragmentArgs。
系统没有这些类名的提示信息,我必须自己记住这些关键字吗?
法典
/** Method used to re-draw the camera UI controls, called every time configuration changes */
@SuppressLint("RestrictedApi")
private fun updateCameraUi() {
// Listener for button used to view last photo
controls.findViewById<ImageButton>(R.id.photo_view_button).setOnClickListener {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
CameraFragmentDirections.actionCameraToGallery(outputDirectory.absolutePath))
}
}
/** Fragment used to present the user with a gallery of photos taken */
class GalleryFragment internal constructor() : Fragment() {
/** AndroidX navigation arguments */
private val args: GalleryFragmentArgs by navArgs()
}
不,如果你知道一个技巧,你不需要自己记住这些东西。
例如,如果您不记得"关键字"Directions
,但您知道要执行与CameraFragment
相关的事情,则可以开始键入例如CameraFragm
在 Android Studio 中。然后,它将为您建议CameraFragment
和CameraFragmentDirections
。这样,即使您不记得关键字Directions
,也可以轻松找到CameraFragmentDirections
。
不过,没有那么多关键字需要担心。使用导航框架一段时间后,您将记住所有这些内容。
如果你好奇,你可以在构建后在这里找到生成的类:
./app/build/generated/source/navigation-args/...
例如,在调试版本之后:
./app/build/generated/source/navigation-args/debug/com/android/example/cameraxbasic/fragments/CameraFragmentDirections.java
如果你更好奇,生成这些类的代码在这里: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/navigation/navigation-safe-args-generator/src/main/kotlin/androidx/navigation/safe/args/generator/java/JavaNavWriter.kt
例如,您可以在那里找到以下代码:
internal fun Destination.toClassName(): ClassName {
val destName = name ?: throw IllegalStateException("Destination with actions must have name")
return ClassName.get(destName.packageName(), "${destName.simpleName()}Directions")
}
这是决定CameraFragmentDirections
获得什么名称的代码。(注"${destName.simpleName()}Directions"
在末尾。