Search code examples
androidkotlinandroid-jetpackandroid-viewbinding

Access another activity's UI element using view binding


I Have an activity having a button "Next" under that I have NavHostController for fragments. I am using that button to navigate though fragments using NavComponemts grapgh. I've set on click lister on button in activity that will call a function in fragment that will navigate to next fragment. But When I am on last fragment I want to hide that button. That the problem.

We can access another activity's UI element simply using kotlin synthetic. When migrating to jetpack view binding I realised that the binding is private to that particular activity , there is no way to do this. There is no documentation about this


Solution

  • But When I am on last fragment I want to hide that button. That the problem.

    You can achieve this by adding a function in parent activity (activity having "Next" button) and call it when your last fragment is displayed.

    In activity :

    fun hideNextBtn() {
        binding.btnNext.isVisible = false
    }
    

    In last fragment :

    (requireActivity() as MainActivity).hideNextBtn()