Un Fragment
dans Android est une subactivité
. Une seule activité
peut héberger plusieurs fragments
. Donc par exemple, si vous avez besoin d'une page principale avec des sous-pages, alors vous devez penser aux Fragments
. Ce qui est intéressant, c'est que les Fragments
ont leur propre cycle de vie et nous fournissent ainsi une manière indépendante de travailler sans avoir à dépendre autant des activités
.
Ce tutoriel enseigne comment utiliser les fragments
via des exemples simples basés sur Kotlin Android.
Exemple 1 : Kotlin Android - Montrer Fragment
dans l'Activity
.
L'activité a un bouton qui, lorsqu'il est cliqué, affiche un fragment. Voici l'image de démonstration de ce qui est créé :
Étape 1 : Dépendances
Aucune dépendance tierce n'est nécessaire pour ce projet.
Step 2 : Conception des mises en page
Vous avez besoin de deux layouts : un pour le fragment
et l'autre pour l'activité
principale.
(a). fragment.xml
C'est le layout pour le fragment
. Il contiendra simplement un textiew :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:text="@string/str_fragment"
android:textColor="#2a2a2a"
android:layout_margin="10dp"
android:padding="10dp"/>
</LinearLayout>
**(b). activity_main.xml
`
C'est le layout pour l'activité principale. Il contiendra un bouton et un framelayout
. Lorsque l'utilisateur clique sur le bouton, et fragment
est initialisé et rendu dans le framelayout
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:text="@string/show"/>
<FrameLayout
android:id="@+id/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1">
</FrameLayout>
</LinearLayout>
Etape 3 : Créer un Fragment
.
La troisième étape consiste à créer le fragment
réel et à gonfler son layout. Un fragment
est créé en étendant la classe androidx.fragment.app.Fragment
. Il est gonflé en surchargeant la fonction onCreateView()
et en retournant un objet de vue gonflé à partir d'un layout pour le fragment
.
Voici le code complet :
Fragment_one.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment.*
class Fragment_one : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment,container,false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
txt_fragment.setOnClickListener {
Toast.makeText(activity,"text fragment",Toast.LENGTH_SHORT).show()
}
}
}
Etape 4 : Créer MainActivity
.
C'est la activité
qui va héberger le fragment
. Les Fragments
n'existent pas par eux-mêmes mais sont hébergés par des activités
. Une seule activité
peut héberger plusieurs fragments
.
Pour afficher un fragment
à l'intérieur d'une activité
, vous devez effectuer ce que l'on appelle une transaction Fragment
. Une telle transaction peut consister à ajouter un fragment
, à supprimer un fragment
, à remplacer un fragment
, etc. Dans notre cas, nous sommes intéressés par le remplacement de notre framelayout
par notre fragment
. Voici le code pour le faire :
fun showFragment(fragment: Fragment_one){
val fram = supportFragmentManager.beginTransaction()
fram.replace(R.id.fragment_main,fragment)
fram.commit()
}
Voici le code complet de cette activité
:
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_show.setOnClickListener {
val fragment = arb.test.fragment.Fragment_one()
showFragment(fragment)
}
}
fun showFragment(fragment: Fragment_one){
val fram = supportFragmentManager.beginTransaction()
fram.replace(R.id.fragment_main,fragment)
fram.commit()
}
}
Exécuter
Maintenant, exécutez le projet.
Référence
Téléchargez le code ci-dessous :
No. | Lien |
---|---|
1. | Télécharger le code |
2. | Suivre l'auteur du code |