我正在实现导航组件,但是当我的片段位于选项卡布局中时,我遇到了一个问题,它显示了这样的错误:
/ action_previousMatchFragment_to_detailMatchFragment对于此NavController未知
class MatchAdapter(private val listMatchItems: List<Match.MatchItem>) :
RecyclerView.Adapter<MatchAdapter.MatchViewHolder>() {
private var itemClickListener:((Match.MatchItem) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchViewHolder {
return MatchViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_match, parent, false
)
)
}
override fun getItemCount(): Int = listMatchItems.size
override fun onBindViewHolder(holder: MatchViewHolder, position: Int) {
val matchItem: Match.MatchItem = listMatchItems[position]
holder.bindItem(matchItem)
holder.itemView.setOnClickListener {
itemClickListener?.invoke(matchItem)
}
}
fun setItemClickListener(listener: (matchItem: Match.MatchItem) -> Unit) {
itemClickListener = listener
}
}
class PreviousMatchFragment : Fragment(), PreviousMatchImpl.View {
private var matchItems: MutableList<Match.MatchItem> = mutableListOf()
private val adapter by lazy {
MatchAdapter(
matchItems
)
}
private lateinit var presenter: PreviousMatchPresenter
private var leagueId: String? = null
fun newInstance(leagueId: String): PreviousMatchFragment {
val bundle = Bundle()
bundle.putString("leagueId", leagueId)
val fragment = PreviousMatchFragment()
fragment.arguments = bundle
return fragment
}
private fun readBundle(bundle: Bundle?) {
if (bundle != null) {
leagueId = bundle.getString("leagueId")
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_last_match, container, false)
arguments?.let { readBundle(it) }
adapter.setItemClickListener {
Navigation.findNavController(view).navigate(PreviousMatchFragmentDirections.actionPreviousMatchFragmentToDetailMatchFragment(leagueId))
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter = PreviousMatchPresenter(this)
leagueId?.let { presenter.getListMatch(it) }
rv_last_match.layoutManager = LinearLayoutManager(context)
rv_last_match.adapter = adapter
}
override fun setDataList(data: List<Match.MatchItem>) {
matchItems.clear()
matchItems.addAll(data)
adapter.notifyDataSetChanged()
}
}
完整错误是:
java.lang.IllegalArgumentException:导航目标com.example.rifqi.footballapp:id / action_previousMatchFragment_to_detailMatchFragment对于此NavController未知
答案 0 :(得分:0)
您正在将R.layout.fragment_last_match
设置为NavController所在的片段。那不是您使用NavController的方式。
您的Navigation.findNavController(view).navigate(PreviousMatchFragmentDirections.actionPreviousMatchFragmentToDetailMatchFragment(leagueId))
应该是
Navigation.findNavController(R.ID.OF_NAV_HOST_FRAGMENT).navigate(PreviousMatchFragmentDirections.actionPreviousMatchFragmentToDetailMatchFragment(leagueId))
其中R.ID.OF_NAV_HOST_FRAGMENT是NavHostFragment的ID,而不仅仅是任何片段。