Android 使用 navigation 时传递参数的两种方式

2022-04-20  本文已影响0人  雁过留声_泪落无痕
  1. 使用 by navArgs()
<navigation>
    <fragment
        android:id="@+id/gallery_fragment"
        android:name="com.google.samples.apps.sunflower.GalleryFragment"
        android:label="@string/plant_details_title"
        tools:layout="@layout/fragment_gallery">
        <argument
            android:name="plantName"
            app:argType="string" />
    </fragment>

</navigation>
val direction = PlantDetailFragmentDirections
                .actionPlantDetailFragmentToGalleryFragment(plant.name)
findNavController().navigate(direction)
class GalleryFragment : Fragment() {
    private val args: GalleryFragmentArgs by navArgs()
    private val xxx = args.plantName
}
  1. 借助 SavedStateHandle
<navigation>
    <fragment
        android:id="@+id/plant_detail_fragment"
        android:name="com.google.samples.apps.sunflower.PlantDetailFragment"
        android:label="@string/plant_details_title"
        tools:layout="@layout/fragment_plant_detail">

        <action
            android:id="@+id/action_plant_detail_fragment_to_gallery_fragment"
            app:destination="@id/gallery_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" />
        <argument
            android:name="plantId"
            app:argType="string" />
    </fragment>
</navigation>
val direction = HomeViewPagerFragmentDirections
                .actionViewPagerFragmentToPlantDetailFragment(plantId)
view.findNavController().navigate(direction)
class PlantDetailFragment : Fragment() {
    private val plantDetailViewModel: PlantDetailViewModel by viewModels()
    private val xxx = plantDetailViewModel.plantId
}
class PlantDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle
) : ViewModel() {
    val plantId: String = savedStateHandle.get<String>("plantId")!!
}
上一篇下一篇

猜你喜欢

热点阅读