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.
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
interface ButtonStateManager{
fun setEnabled(enabled: Boolean)
}
class Activity0: AppCompatActivity(), ButtonStateManager {
...
override fun setEnabled(enabled: Boolean) {
binding.popUpButton.isEnabled = enabled
}
}
Fragment
asoverride 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)
}