Access another activity's UI element using view binding

Viewed 641

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

2 Answers

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()

I am not sure why you want to access or do any change on any UI element from anywhere other than the Activity or Fragment it is part of. It might lead to. bugs.

Still if you want you can make the DataBinding object you get when calling DataBinding.setContentView() public or provide a getter method to access the same.

Related