簡體   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