Android-I可以从片段访问ViewModel方法,但该方法不返回列表方法、片段、但该、列表

2023-09-04 01:38:53 作者:年少怎能不多情

我最近开始研究Android Kotlin,我希望这会有一个非常简单的答案,但我有一个ViewModel,它有一个名为getDataComment的方法,我想从我的片段中调用该方法,并为它提供所需的参数。但当我尝试调用它时,没有生成错误,它只是没有显示列表。

我在视图模型中的方法:

fun getDataComment(postId: Int) {
        PostRepository().getDataComment(postId).enqueue(object : Callback<List<Comment>>{
            override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
                val comments = response.body()
                comments?.let {
                    mPostsComment.value = comments!!
                }
            }

            override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
                Log.e(TAG, "On Failure: ${t.message}")
                t.printStackTrace()
            }
        })
    }
android隐藏系统ui 如何在非库存设备上获取Android的系统UI调谐器

片段类

class PostDetailFragment : Fragment() {

    var param2: Int = 0
    private lateinit var binding: FragmentPostDetailBinding
    private val viewModel by viewModels<PostCommentViewModel>()

    private val gson: Gson by lazy {
        Gson()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_post_detail, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        checkArguments()
    }

     private fun checkArguments() {
        arguments?.let { bundle ->
            if (bundle.containsKey("POST")) {
                val postString = bundle.getString("POST", "")
                val post: Post = gson.fromJson(postString, Post::class.java)

                binding.postDetailstvTitle.text = post.title
                binding.postDetailstvBody.text = post.body
                param2 = post.id

                viewModel.getDataComment(param2)
            }
        }
    }
}
它应该是这样的:1 以下是我得到的信息:2

如果这里很乱,请提前道歉这是我第一次在这里询问,如果您需要更多信息,请告诉我。谢谢!

推荐答案

观察视图模型中的mPostsComment内部片段

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    checkArguments()

    viewModel.mPostsComment.observe(viewLifecycleOwner, { collectionList ->
                // do whatever you want with collectionList
    })
}