当用户单击项目时,我正在尝试从回收者视图传递与该项目相关的对象。我可以以某种方式更改片段,但将空值传递给第二个片段。 这是我的片段,其中包含回收站视图
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_movie_list, container, false)
rootView.rvMovieList.layoutManager = LinearLayoutManager(activity)
rootView.rvMovieList.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
val moviesList = listOf(
Movies("Civil War", "Chris Evans", 2016, 7.8),
Movies("Avengers", "RDJ", 2012, 8.1),
Movies("Age of Ultron", "Chris Evans", 2015, 7.2),
Movies("Infinity War", "RDJ", 2018, 8.9),
Movies("Aquaman", "Jason Momoa", 2018, 8.3)
)
val adapter = MovieDetailsAdapter(context, moviesList)
rootView.rvMovieList.adapter = adapter
return rootView
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnItemClickListener)
listener = context
}
interface OnItemClickListener {
fun onItemClickListener(instanceList: Movies)
}
companion object {
val context = this
lateinit var clickedInstance: Movies
lateinit var listener: OnItemClickListener
}
这是适配器。当我单击项目时,侦听器必须将与单击的项目相关的对象传递给第二个片段。
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
return MovieViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.recycler_view_movie_list, parent, false
)
)
}
override fun getItemCount(): Int {
return movieNames.size
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
holder.setData(movieNames[position])
}
inner class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var currName: Movies
init {
itemView.setOnClickListener {
}
}
fun setData(movieName: Movies) {
itemView.tvRVMovieLists.text = movieName.title
this.currName = movieName
}
}
这是第二个片段
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_movie_details, container, false)
arguments?.run {
rootView.tvTitle?.text = getString("MOVIE_TITLE")
rootView.tvActor?.text = getString("MOVIE_ACTOR")
rootView.tvYear?.text = getInt("MOVIE_YEAR").toString()
rootView.tvRating?.text = getDouble("MOVIE_RATING").toString()
}
return rootView
}
我尝试将接口侦听器作为伴侣对象。它只是打开第二个片段。但是数据没有传递。
答案 0 :(得分:0)
您不能直接从一个片段到另一个片段进行通信,您应该将数据从片段A传递到其活动,然后再将数据从活动传递到片段B。