这里有来 self 的 Activity 和片段的代码:
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
}
}
}
片段:
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)
}
...
}
在这里,我尝试将按钮的状态更改为在片段启动时启用。但是,每当我的片段运行时,应用程序就会崩溃并返回到主 Activity (应用程序的启动)。为什么尝试从我的片段访问我的 Activity 中的按钮会导致应用程序崩溃。感谢您抽出宝贵的时间,我们非常感谢您的帮助。
最佳答案
您永远不会创建Activity
对象,这是操作系统的责任。所以永远不要执行Activity0()
。在片段中,您可以使用 activity
属性访问关联的 Activity。
就您的问题而言,可以这样解决
定义接口(interface)
interface ButtonStateManager{
fun setEnabled(enabled: Boolean)
}
让你的Activity实现这个接口(interface)
class Activity0: AppCompatActivity(), ButtonStateManager {
...
override fun setEnabled(enabled: Boolean) {
binding.popUpButton.isEnabled = enabled
}
}
现在您可以从 Fragment
启用/禁用按钮
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)
}
关于android-studio - 从片段更改 Activity 的按钮状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69126047/