Android Jetpack 导航 Controller |获取当前目的地的操作列表

标签 android kotlin androidx android-jetpack android-jetpack-navigation

我正在创建一个组合应用,它使用 Android 的新 Jetpack Navigation NavController。我创建了一个带有 RecyclerView 的 fragment ,其中将填充 View ,您可以单击这些 View 以导航到各种应用程序演示(如果我能弄清楚的话,也许还有我制作的实际应用程序)。我目前正在手动填充列表,但我想自动执行该过程。

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 的私有(private)属性,其中包含与 NavDestination 关联的 NavActions

我通过使用反射来访问它来解决这个问题。

    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

关于Android Jetpack 导航 Controller |获取当前目的地的操作列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61418924/

相关文章:

android - 如何信任 Worklight 6.2 上的所有 ssl 证书

android - 密码保护Android应用程序的启动

list - 如何根据 kotlin/java 中的另一个列表过滤列表?

java - 单击按钮时显示/隐藏 ImageView

android - MVVM:从内部 fragment 更新viewpager2的容器 View

android - 使用 navhost 时无法更改工具栏后退图标

android - Splashscreen API 未显示图标

android - 重构为 AndroidX 后布局预览不起作用

android - 当我不使用 ContigouslyPagedList 时,ContigouslyPagedList onPageError

Android:如何获取当前的前台 Activity (来自服务)?