将值从 Activity 传递到 Fragment

Passing Value from Activity to Fragment

我的项目中有底部导航 activity 并且包含两个片段。我正在尝试从 Activity--->FragmentOne 传递值,然后从 FragmentOne--->FragmentTwo 传递值。感谢任何帮助。

使用的语言

Kotlin

预期

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

错误

Null Pointer Exception

代码

Activity

    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)
    }

TestFragmentOne

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

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

    static final Intent storageIntent = new Intent();

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

您可以采用多种方式,但考虑到您当前的实现(使用 newInstance),我会使用您的 parent activity 作为调解器,如下所示:

1) 创建一个 BaseFragment class,您的 TestFragmentOne 和 TestFragmentTwo 将对其进行扩展,并在其中包含对您的 parent 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"
      }
 }