Android Jetpack NavController |获取当前目标的操作列表

问题描述 投票:0回答:1

我正在创建一个使用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获取实际的类将是痛苦。

提前感谢

android kotlin navigation androidx jetpack
1个回答
0
投票

这可能被认为有点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

© www.soinside.com 2019 - 2024. All rights reserved.