android - 将价值从活动传递到片段
问题描述
我的项目中有底部导航活动并包含两个片段。我正在尝试从 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"
}
}
推荐阅读
- php - Codeigniter - 根据年份获取表中列的总和,并应将其显示在输入标签中
- node.js - 制作群组视频通话应用程序 wrtc vs mediasoup
- javascript - React.js 鼠标,触摸事件不仅适用于手机屏幕
- docker - Kubernetes https://registry-1.docker.io/v2/:拨号tcp:查找registry-1.docker.io:名称解析暂时失败
- python - python xlsxwriter 独特的填充颜色
- python - b'\xffff' 和 b'\xff\xff' 有什么区别?
- android - 登录后如何在firebase中上传用户个人资料图片?
- firebase - LateInitializationError:字段“chatRoomStream”尚未初始化
- java - 将一个 LinkedList 附加/连接到另一个 LinkedList 后面的最有效方法?
- windows - 清理 C:\ProgramData\Microsoft\VisualStudio\Packages 的正确、安全的方法是什么?