如何从碎片和活动中传递价值并获得价值 [英] How to pass and get value from fragment and activity

查看:82
本文介绍了如何从碎片和活动中传递价值并获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过片段和活动获得价值?

How to pass and get value from fragment and activity?

推荐答案

这是Android Studio建议的解决方案(=当您使用文件创建Blank-Fragment-> New-> Fragment-> Fragment(Blank)并检查包括片段工厂方法").

Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").

将其放入片段中

class MyFragment: Fragment {

...

    companion object {

            @JvmStatic
            fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
                arguments = Bundle().apply {
                    putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
                }
            }
     }
}

.apply是创建对象或设置为

.apply is a nice trick to set data when an object is created, or as they state here:

this值作为接收者调用指定的函数[block] 并返回this值.

Calls the specified function [block] with this value as its receiver and returns this value.

然后在活动"或片段"中执行以下操作:

Then in your Activity or Fragment do:

val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here

并读取片段中的参数,例如:

and read the Arguments in your Fragment such as:

private var isMyBoolean = false

override fun onAttach(context: Context?) {
    super.onAttach(context)
    arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
        isMyBoolean = it
    }
}

享受科特林的魔力!

这篇关于如何从碎片和活动中传递价值并获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆