我正在创建一个使用Android新的Jetpack导航NavController
的投资组合应用。我创建了一个带有RecyclerView
的片段,该片段中将填充视图,您可以单击这些视图来导航至各种应用程序演示(如果我能弄清楚的话,也许是我制作的实际应用程序)。我目前正在手动填充列表,但我想使该过程自动化。
class PortfolioFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_portfolio, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = view.findNavController()
val currentDestination = navController.currentDestination
// How get list of actions?
val appActions = listOf(
R.id.action_portfolioFragment_to_testFragment
)
portfolio_app_list.layoutManager = LinearLayoutManager(context)
portfolio_app_list.adapter = PortfolioAdapter(appActions)
}
}
我在NavGraph
上找不到任何方法,也没有NavDestination
来获取currentDestination
可用的动作列表。我知道我的navigation_main.xml
有它们,并且我可以使用XMLPullParser
或类似的东西来获取它们,但是我可能会开始使用Safe Args plugin,这意味着从XML获取实际的类将是痛苦。
提前感谢
这可能被认为有点hacky。
[NavDestination
具有称为mActions
的私有属性,其中包含与NavActions
关联的NavDestination
。
我通过使用反射来访问它来解决此问题。
val currentDestination = findNavController().currentDestination
val field = NavDestination::class.java.getDeclaredField("mActions")
field.isAccessible = true
val fieldValue = field.get(currentDestination) as SparseArrayCompat<*>
val appActions = arrayListOf<Any>()
fieldValue.forEach { key, any ->
appActions.add(any)
}
[NavActions
作为SparseArrayCompat
返回,然后进行迭代以获得List