首页 > 解决方案 > 将价值从活动传递到片段

问题描述

我的项目中有底部导航活动并包含两个片段。我正在尝试从 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")

标签: androidandroid-fragmentskotlinandroid-fragmentactivitykotlin-android-extensions

解决方案


您可以采用多种方式,但考虑到您当前的实现(使用 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"
      }
 }

推荐阅读