美文网首页
Android 使用 navigation 时传递参数的两种方式

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

作者: 雁过留声_泪落无痕 | 来源:发表于2022-04-20 08:22 被阅读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")!!
    }
    

    相关文章

      网友评论

          本文标题:Android 使用 navigation 时传递参数的两种方式

          本文链接:https://www.haomeiwen.com/subject/kiteertx.html