Junior
Jak předat parametry do fragmentu?
sobes.tech AI
Odpověď od AI
Bundle se používá k balení párů klíč-hodnota.
// Vytvoření fragmentu s argumenty
val fragment = MyFragment().apply {
arguments = Bundle().apply {
putString("key1", "value1")
putInt("key2", 123)
}
}
// Předání fragmentu do FragmentManager
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
Získání parametrů ve fragmentu:
// V onCreate nebo 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žití získaných hodnot
}
// ...
return inflater.inflate(R.layout.fragment_my, container, false)
}
Doporučený způsob s použitím tovární metody a Kotlin:
// Fragment s tovární metodou
class MyFragment : Fragment() {
// Získání argumentů
private val key1: String? by lazy { arguments?.getString("key1") }
private val key2: Int by lazy { arguments?.getInt("key2", 0) ?: 0 }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Použití získaných hodnot
val text = "Hodnota 1: $key1, Hodnota 2: $key2"
// ...
return inflater.inflate(R.layout.fragment_my, container, false)
}
companion object {
// Tovární metoda
@JvmStatic
fun newInstance(param1: String, param2: Int): MyFragment {
return MyFragment().apply {
arguments = Bundle().apply {
putString("key1", param1)
putInt("key2", param2)
}
}
}
}
}
Použití tovární metody:
// Vytvoření fragmentu s tovární metodou
val fragment = MyFragment.newInstance("nová hodnota", 456)
// Předání fragmentu do FragmentManager
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()