函数Navigation.findNavController()
在代码A中需要一个activity
参数,但是我只能通过context
获得一个itemView.context
。
如何在Android Studio中从activity
获得RecyclerView.ViewHolder(itemView)
?
目前,我必须将private val mactivity: activity
从代码B传递到代码A,它可以工作,但是我认为这不是一个好方法。
添加的内容:
致Miriana Itani:谢谢!
您的代码运行良好。我粘贴了FrameLayout xml文件,可以看到代码C
我很奇怪,代码Navigation.findNavController(temView)...
是如何找到NavController控件的? 你能告诉我吗?
您知道使用代码Navigation.findNavController(mactivity,R.id.fragment_container)
很容易理解,因为NavController的ID是fragment_container
,而且是唯一的。
代码A
class VideoListAdapter (private val videoList: List<File>,private val mactivity: activity) : RecyclerView.Adapter<VideoListAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): VideoListAdapter.MyViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.layout_fragment_video_list_recycleview,parent,false)
return MyViewHolder(v)
}
override fun onBindViewHolder(holder: VideoListAdapter.MyViewHolder,position: Int) {
holder.bindItems(videoList[position])
}
override fun getItemCount(): Int {
return videoList.size
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aFile: File) {
itemView.tvVideoFileName.text=aFile.name
itemView.btnPlay.setOnClicklistener {
Navigation.findNavController(mactivity,R.id.fragment_container).navigate(
UIFragmentVideoListDirections.aVideoList2Video((aFile.absolutePath)) )
}
}
}
}
代码B
class UIFragmentVideoList : Fragment() {
private lateinit var listFile: MutableList<File>
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.layout_fragment_video_list,container,false)
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
val outputDirectoryOfVideo = getVideoOutputDirectory(requireContext())
listFile =outputDirectoryOfVideo.listFiles{file -> VIDEO_EXTENSION_WHITELIST.contains(file.extension.toUpperCase())}
.sorted().reversed().toMutableList()
videoRecyclerView.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.VERTICAL,false)
val aVideoListAdapter=VideoListAdapter(listFile,requireactivity())
videoRecyclerView.adapter=aVideoListAdapter
}
}
代码C
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment
android:id="@+id/fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</FrameLayout>