Junior
Ako odovzdať parametre do fragmentu?
sobes.tech AI
Odpoveď od AI
Bundle sa používa na balenie párov kľúč-hodnota.
// Vytvorenie fragmentu s argumentmi
val fragment = MyFragment().apply {
arguments = Bundle().apply {
putString("key1", "value1")
putInt("key2", 123)
}
}
// Odovzdanie fragmentu do FragmentManager
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
Získanie parametrov vo fragmente:
// V onCreate alebo onCreateView fragmentu
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
arguments?.let {
val value1 = it.getString("key1")
val value2 = it.getInt("key2")
// Použitie získaných hodnôt
}
// ...
return inflater.inflate(R.layout.fragment_my, container, false)
}
Odporúčaný spôsob s použitím továrenského metódu a Kotlinu:
// Fragment s továrenskou metódou
class MyFragment : Fragment() {
// Získanie argumentov
private val key1: String? by lazy { arguments?.getString("key1") }
private val key2: Int by lazy { arguments?.getInt("key2", 0) ?: 0 } // Predvolená hodnota
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Použitie získaných hodnôt
val text = "Hodnota 1: $key1, Hodnota 2: $key2"
// ...
return inflater.inflate(R.layout.fragment_my, container, false)
}
companion object {
// Továrenská metóda
@JvmStatic // Pre volanie z Javy
fun newInstance(param1: String, param2: Int): MyFragment {
return MyFragment().apply {
arguments = Bundle().apply {
putString("key1", param1)
putInt("key2", param2)
}
}
}
}
}
Použitie továrenskej metódy:
// Vytvorenie fragmentu s továrenskou metódou
val fragment = MyFragment.newInstance("nová hodnota", 456)
// Odovzdanie fragmentu do FragmentManager
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()