繁体   English   中英

将值从 Activity 传递到 Fragment

[英]Passing Value from Activity to Fragment

我的项目中有底部导航活动并包含两个片段。 我试图从 Activity--->FragmentOne 传递值,然后从 FragmentOne--->FragmentTwo。 任何帮助表示赞赏。

使用的语言

Kotlin

期待

1)Pass value from Activity to Fragment
2)Send value from Fragment to Fragment

错误

Null Pointer Exception

代码

活动

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        var testName:String=intent.getStringExtra("name")
        println("TestCLLicked: $testName")
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
        replaceFragment(TestFragmentOne.newInstance(),TestFragmentOne.TAG)
    }

测试片段一

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            var st:String=arguments!!.getString("name")
             println("TestCLLicked: $testName")

您可以采用多种方式,但鉴于您当前的实现(使用 newInstance),我会使用您的父活动作为中介,如下所示:

1) 创建一个 BaseFragment 类,您的 TestFragmentOne 和 TestFragmentTwo 将扩展该类,并在其中包含对您的父 Activity 的引用(此处命名为“MainActivity”):

abstract class BaseFragment : Fragment() {

     lateinit var ACTIVITY: MainActivity

     override fun onAttach(context: Context) {
         super.onAttach(context)
         ACTIVITY = context as MainActivity
     }
}

2) 然后,在您的 Activity 中确保将变量声明为字段:

class MainActivity : AppCompatActivity() {

     var textVariable = "This to be read from the fragments"
     ...
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         textVariable = "I can also change this text"
         ...
     }
}

3) 然后,从每个片段中,您可以使用从 BaseFragment 继承的实例访问您的变量:

 class TestFragmentOne : BaseFragment() {

      override fun onActivityCreated(savedInstanceState: Bundle?) {
          super.onActivityCreated(savedInstanceState)
          val incomingText = ACTIVITY.textVariable
          println("Incoming text: "+incomingText)

          // You can also set the value of this variable to be read from 
          // another fragment later
          ACTIVITY.textVariable = "Text set from TestFragmentOne"
      }
 }

对于这种情况,我使用静态 Intent 并根据需要通过它传输数据。

    static final Intent storageIntent = new Intent();

    storageIntent.putExtra("name", "value");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM