如何将数据从片段转移到Kotlin的活动?

发布于 2025-02-07 05:47:16 字数 37 浏览 1 评论 0原文

基本上,我正在尝试从碎片中改变我的主动脉的变量。我该怎么做?

Basically I'm trying to change a variable in my MainActivity from a Fragment. How would I go about doing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

要走就滚别墨迹 2025-02-14 05:47:16

如果您的片段与MainActivity相关联,则可以通过使用sirceepontivity() .ie:
获得片段。
在您的主动脉中:

class MainActivity : AppCompatActivity() {
  var temp = "sth"
}

然后在片段中,您可以访问变量

(requireActivity() as MainActivity).temp

If your fragment is associated with MainActivity, you can get the fragmentActivity by using requireActivity().i.e.:
In your MainActivity:

class MainActivity : AppCompatActivity() {
  var temp = "sth"
}

Then in your Fragment, you can access the variable by

(requireActivity() as MainActivity).temp
半衬遮猫 2025-02-14 05:47:16

因此,基本上,不要使用FragmentBinding的东西。

始终使用view.findViewById<>(r.id.name),

然后覆盖otCreateview函数,在该函数中,您可以调用(sighteactivity(sirceeactivity()作为mainActivity)。

您还可以更改活动本身中变量的值。

这使我太久了,无法弄清楚大声笑,希望这对其他人有帮助。

So basically, don't use the fragmentBinding thingy.

Always use the view.findViewByID<>(R.id.name)

then override the onCreateView function and in that function you can call (requireActivity() as MainActivity).theVariableYouWantToGet to get the variable you want.

You can also change the value of the variable in the Activity itself.

This took me wayy too long to figure out lol, hope this will help other people.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文