未连接适配器但已在片段上设置

时间:2021-06-08 12:17:42

标签: android kotlin android-recyclerview

我以前遇到过很多次,但这一次有点令人沮丧。我已经改变了附加适配器的顺序:setLayoutManager first;首先观察视图模型;没有任何效果。 viewmodel 函数也没有被观察到。这是我的代码:

class FavoriteMoviesFragment : Fragment() {

companion object {
    fun newInstance() = FavoriteMoviesFragment()
}

private val viewModel: FavoriteMoviesViewModel by viewModels()
private var favmovieAdapter = MoviesAdapter(object : MovieClickListener {
    override fun onMovieClicked(movie: Movies?) {
        viewModel.onMovieClicked(movie)
    }
})

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val recyclerView = view?.findViewById<RecyclerView>(R.id.rvFavMovies)
    Log.d("favAdapter", "Adapter attached $favmovieAdapter")
    recyclerView?.layoutManager = LinearLayoutManager(activity?.applicationContext)
    recyclerView?.setHasFixedSize(true)
    recyclerView?.adapter = favmovieAdapter
    vmSetup()
    return inflater.inflate(
        R.layout.favorite_movies_fragment,
        container, false
    )
}

fun vmSetup() {
    viewModel.getFavMovies().observe(viewLifecycleOwner, { movielist ->
        if (movielist != null) {
            Log.d("pagedFavList", "List size: ${movielist.size}")
            favmovieAdapter.submitList(movielist)
            favmovieAdapter.notifyDataSetChanged()
        } else {
            Toast.makeText(context, "Data Loading Always Failed", Toast.LENGTH_SHORT).show()
        }
    })
    viewModel.navigatetoDetail().observe(viewLifecycleOwner, { movies ->
        if (movies != null) {
            val action =
                FavoriteFragmentDirections.actionFavoriteFragmentToDetailFragment(movies, null)
            Navigation.findNavController(requireView()).navigate(action)
            viewModel.onMovieDetailNavigated()
        }
    })
}

有解决这个问题的想法吗?

2 个答案:

答案 0 :(得分:2)

我想我明白了。您正在尝试从视图中找到 recycleview 适配器,然后再对其进行充气。所以

view?.findViewById<RecyclerView>(R.id.rvFavMovies)

只返回空值。因此,它之后的所有内容都变为空。

相反,试试这个:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val view = inflater.inflate(
        R.layout.fragment_favorite_movies,
        container, false
    )


    val recyclerView = view?.findViewById<RecyclerView>(R.id.rvFavMovies)
    Log.d("favAdapter", "Adapter attached $favmovieAdapter")
    recyclerView?.layoutManager = LinearLayoutManager(activity?.applicationContext)
    recyclerView?.setHasFixedSize(true)
    recyclerView?.adapter = favmovieAdapter
    vmSetup()
    return view
}

答案 1 :(得分:0)

您应该使用adapter.observe{} 函数。在observe里面,你可以把notify数据改变。

您可以在

中了解有关此的更多信息

https://developer.android.com/topic/libraries/architecture/livedata