javaandroidandroid-studioandroid-activityandroid-fragmentactivity

How to access the fragments button from hosting activity in android?


I have few fragments hosted by an acticity, i want to access specific fragments' button on the fragment view from the hosting activity

from the fragment i can access activitie's button like this

btnSubmit = (MaterialButton) getActivity().findViewById(R.id.submit_btn);

i want to do the inverse of this, is there any method to do this?


Solution

  • The proper way to do something with the fragment from the activity would be as follows

    Fragment

    class MyFragment: Fragment(){
    
        var button: Button? = null
    
        override fun onCreateView(){
            ...
            button = view.findViewById(..)
        }
    
        fun disable(){
            button.enabled = false
        }
    }
    

    Activity

    using the fragment manager find the fragment by its id (or other means) and cast it as your fragment

    then call the method of that fragment (see MyFragment above) to disable the button

    class MainActivity: AppCompatActivity(){
    
        fun disableFragmentButton(){
            val fragmentId = adapter.getItemId(positionOfYourFragmentInTheAdapter)
            if(fragmentId > -1){
                (supportFragmentManager.findFragmentById(fragmentId) as MyFragment).disable()
            }
        }
    }
    

    You should always avoid directly accessing UI components of the fragment from the activity