# 2020-04-20 | Kotlin | Fragments
###### tags: `kotlin` `android` `gobelins` `fragments`
## Exercice
### Enoncé
* Créer deux fragments ChoiceFragment et ComputationFragment
* Le premier fragment doit contient 4 boutons correspondant chacun à une opération
* Le second fragment contient deux champs permettant de saisir les membres de l’opération, un bouton pour exécuter l’opération et un label pour afficher le résultat de l’opération
* Quand l’utilisateur clique sur un bouton, lancer le second fragment en passant en paramètre l’opération correspondant au bouton
### Code
#### ChoiceFragment.kt
Fragment de séléction de l'opération.
```kotlin
class ChoiceFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_first,container,false).apply {}
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var parent = view.findViewById<ConstraintLayout>(R.id.parent)
parent.children.forEach { it ->
if(it.tag == "btn") {
it.setOnClickListener {
activity?.change(ComputationFragment.newInstance((it as Button).text as String))
}
}
}
}
}
```
#### Computationfragment
Fragement de saisie des nombres et du calcul et affichage du résultat.
```kotlin
class ComputationFragment: Fragment() {
val operation: String by lazy {
arguments?.getString(ARGS_OPERATION, "+") ?: "+"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.second_fragment,container,false)
}
companion object {
const val ARGS_OPERATION = "ARGS_OPERATION"
fun newInstance(operation: String):ComputationFragment {
return ComputationFragment().apply {
//On sauvegarde l’opération dans les arguments,
//Si le fragment se recrée, la valeur sera restaurée
arguments = bundleOf(ARGS_OPERATION to operation)
}
}
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val nb1 = view.findViewById<EditText>(R.id.first_nb)
val nb2 = view.findViewById<EditText>(R.id.second_nb)
view.findViewById<Button>(R.id.btnresult).setOnClickListener {
text_result.text = "Voici le résultat : ${nb1.text} ${arguments?.getString(ARGS_OPERATION)} ${nb2.text}"
}
}
}
```
## Exercie
### Enoncé
Faire en sorte que les données se conservent même avec la rotation de l'écran.
### Code