如何使用 Kotlin 将数据从片段传输到 Android 中的 activity?
How to tranfer data from fragment to activity in Android using Kotlin?
这是我的代码:-
class ACFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val id = "ac"
fb_ac.setOnClickListener {
val intent = Intent(this@ACFragment, AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return inflater.inflate(R.layout.fragment_ac, container, false)
}
}
我想使用 Intent 将数据从片段传输到 activity,但我做不到。有人可以帮我吗?
您可以通过调用 getStringExtra
方法在 AddFunction
activity 中检索 id
字符串:
override fun onCreate(savedInstanceState: Bundle) {
...
val id = intent.getStringExtra("id") ?: ""
}
此外,您应该像这样更改 onCreateView
声明:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_ac, container, false)
val id = "ac"
view.findViewById<Button>(R.id.fb_ac).setOnClickListener {
val intent = Intent(requireContext(), AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return view
}
这是我的代码:-
class ACFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val id = "ac"
fb_ac.setOnClickListener {
val intent = Intent(this@ACFragment, AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return inflater.inflate(R.layout.fragment_ac, container, false)
}
}
我想使用 Intent 将数据从片段传输到 activity,但我做不到。有人可以帮我吗?
您可以通过调用 getStringExtra
方法在 AddFunction
activity 中检索 id
字符串:
override fun onCreate(savedInstanceState: Bundle) {
...
val id = intent.getStringExtra("id") ?: ""
}
此外,您应该像这样更改 onCreateView
声明:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_ac, container, false)
val id = "ac"
view.findViewById<Button>(R.id.fb_ac).setOnClickListener {
val intent = Intent(requireContext(), AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return view
}