【问题标题】:How to safeargs in viewModel Kotlin Android?如何在 viewModel Kotlin Android 中保护参数?
【发布时间】:2021-01-03 09:41:31
【问题描述】:

我的 MVVM 结构有问题。我创建应用程序并在片段之间传递数据。现在它工作正常,但我需要将此逻辑添加到我的 ViewModel。

这是我的 NotesClickFragment:

@AndroidEntryPoint
class NotesClickFragment : Fragment(R.layout.fragment_click_notes) {

    private val args by navArgs<NotesClickFragmentArgs>()

    private val viewModel: NotesClickViewModel by viewModels()
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = FragmentClickNotesBinding.bind(view)


        binding.apply {
            textViewTitleClick.setText(args.notesClickArgs.titleNotes)
            textViewContentNotesClick.setText(args.notesClickArgs.contentNotes)
            textViewHistoryClick.setText(args.notesClickArgs.createdNotesDateFormat)
        }
    }
}

这是我的 NotesClickViewModel:

class NotesClickViewModel @ViewModelInject constructor(
            private val notesDao: NotesDao
    
    ) : ViewModel() {
    
 }

我正在尝试添加一个私有参数val navArgs: NotesClickFragmentArgs 并创建其他函数来从片段中设置数据,但它不起作用。什么是好的做法?提前感谢您的提示。

【问题讨论】:

  • 如果我需要 ViewModel 中 navArgs 的内容,我将它们作为 Bundle 传递给 ViewModel 的构造函数
  • 这个答案应该可以帮助stackoverflow.com/a/64814055/764624

标签: android kotlin android-safe-args


【解决方案1】:
  1. NotesDao 在 ViewModel 中没有位置,而应该在 Repository 中。

    有关 MVVM 的更多信息,请阅读以下内容:Guide to app architecture

  2. 据我所知,这里不能使用 ViewModel。导航应该在 Fragment 本身内部处理。 为了使用 SafeArgs,您首先需要在 NavGraph 中声明参数,然后您可以使用 Directions 导航到可以传递必要数据的片段。

例如。假设我在 RecyclerView 中有电影列表。当我点击任何我想看的电影时,id 我点击了一个新片段。

  • 第 1 步:在 NavGraph 中声明信息

这就是在我的 NavGraph 中声明 Fragment 的方式。标签argument 表示这个Fragment 接受Int(id)

<fragment
 android:id="@+id/movieDetailsFragment" 
 android:name="my.test.MovieDetailsFragment"
 android:label="fragment_movie_details"
 tools:layout="@layout/fragment_movie_details">
 <argument
  android:name="id"
  app:argType="integer" />
</fragment>

然后,在连接到MovieDetailsFragment 的任何其他 Fragment 中,我只需使用 Directions 并传递我需要的 id

val direction = MoviesPopularFragmentDirections.actionPopularFragmentToMovieDetailsFragment(id = movie.id)
this.findNavController().navigate(direction)

应该就是这样。

同样,官方文档中的更多信息Navigation Safe Args

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2012-05-03
    • 1970-01-01
    相关资源
    最近更新 更多