无法将数据从回收器视图适配器传递到另一个 Kotlin 片段



我正试图从活动转移到片段

在旧的活动应用程序中,当用户点击项目时,他将转到具有项目数据的新活动

现在我需要同样的东西在碎片

这是我的适配器代码

override fun onBindViewHolder(holder: PhotosHolder, position: Int) {
val productPhoto = photosArrayList[position]
val key = productPhoto.key
val name = productPhoto.name
val price = productPhoto.price
val photo = productPhoto.photo
val photo2 = productPhoto.photo2
val photo3 = productPhoto.photo3
val link = "http://suleimanmf.com/Photos/"
holder.key.text = key
holder.name.text = name
holder.price.text = price
holder.photo = photo
holder.photo2 = photo2
holder.photo3 = photo3
holder.container.setOnClickListener {
goToProductInfo(productPhoto)
}
}
private fun goToProductInfo(info: Photo) {
val photosFragment = PhotosFragment()
val bundle = Bundle()
bundle.putString("key", info.key)
bundle.putString("name", info.name)
bundle.putString("price", info.price)
bundle.putString("photo", info.photo)
bundle.putString("photo2", info.photo2)
bundle.putString("photo3", info.photo3)
photosFragment.arguments = bundle
(context.applicationContext as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}
// Old activity
/**
val intent = Intent(context, ProductInfoActivity::class.java)
intent.putExtra("key", info.key)
intent.putExtra("name", info.name)
intent.putExtra("price", info.price)
intent.putExtra("photo", info.photo)
intent.putExtra("photo2", info.photo2)
intent.putExtra("photo3", info.photo3)
startActivity(context, intent, null)
*/
}
}

当我点击项目时,我得到这个错误

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.suleimanmf.gazarcustomers, PID: 5389
java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.suleimanmf.gazarcustomers.ui.gallery.adapter.PhotosAdapter.goToProductInfo(PhotosAdapter.kt:97)
at com.suleimanmf.gazarcustomers.ui.gallery.adapter.PhotosAdapter.onBindViewHolder$lambda-0(PhotosAdapter.kt:80)

抱歉我的英语不好

提前感谢

主要问题是获取应用程序上下文并将其强制转换为MainActivity,这是不可能的,因为名称只声明了它的应用程序上下文。事实上,当你想处理碎片时,唯一有责任将碎片保存在里面的组件就是活动实例。因此,您唯一需要做的就是替换以下代码行:

(context.applicationContext as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}

带有以下代码行:

(context as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}

然后您的代码将正常工作。

相关内容

  • 没有找到相关文章

最新更新