将价值从活动传递到碎片

时间:2019-01-03 18:19:19

标签: android android-fragments kotlin android-fragmentactivity kotlin-android-extensions

我的项目中有底部导航活动,其中包含两个片段。我试图从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)
    }

TestFragmentOne

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

2 个答案:

答案 0 :(得分:0)

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

1)创建一个BaseFragment类,您的TestFragmentOne和TestFragmentTwo将扩展该类,并在其中保留对父活动的引用(此处称为“ MainActivity”):

abstract class BaseFragment : Fragment() {

     lateinit var ACTIVITY: MainActivity

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

2)然后,确保在“活动”中将变量声明为字段:

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

答案 1 :(得分:-2)

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

  code upc    desc desc1   desc2 desc3   desc4
1   12   5    meat  fish chicken        shrimp
2   15   4    fish  meat  shrimp              
3   14   2 chicken           veg          meat
4   13   3     veg          fish              
5   11   1  shrimp          meat       chicken