Search code examples
android-studiokotlinandroid-fragmentsandroid-activityandroid-button

Change activity's button state from fragment


Here I have code from both my activity and my fragment:

Activity:

class Activity0: AppCompatActivity() {
   private lateinit var binding: Activity0Binding
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)                                    
      binding = Activity0Binding.inflate(layoutInflater)
      setContentView(binding.root)

      binding.popUpButton.setOnClickListener {
        supportFragmentManager.commit {
            replace(R.id.quiz_fragment_container, Activity0FragmentNull())
        }
        binding.popUpButton.isEnabled = false
      }
   }
}

Fragment:

class Activity0FragmentNull : Fragment() {
   ...
   override fun onCreateView(
     inflater: LayoutInflater, container: ViewGroup?,
     savedInstanceState: Bundle?
   ): View? {
       Activity0().popUpButton.isEnabled = true
       return inflater.inflate(R.layout.activity0_null, container, false)
   }
   ...
}

Here I am trying to change the state of my button to be enabled whenever the fragment is launched. However, whenever my fragment is run the app crashes and returns to the main activity (start of the app). How come trying to reach a button in my activity from my fragment is causing the app to crash. Thank you for your time and any help is appreciated.


Solution

  • You never create Activity objects, that is the responsibility of the operating system. so never do Activity0(). in a fragment you can access the associated Activity by using the activity property.

    As of your problem it can be solved as

    Define an interface

    interface ButtonStateManager{
        fun setEnabled(enabled: Boolean)
    }
    

    Make your Activity implement this interface

    class Activity0: AppCompatActivity(), ButtonStateManager {
        
        ...
    
        override fun setEnabled(enabled: Boolean) {
             binding.popUpButton.isEnabled = enabled
        }
    }
    

    Now you can enable/disable the button from Fragment as

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
         super.onViewCreated(view, savedInstanceState)
         /* cast the activity to ButtonStateManager and then call the function */
         (activity as? ButtonStateManager)?.setEnabled(true)  
    }