Académique Documents
Professionnel Documents
Culture Documents
– Cours 4 –
Chapitre 2 : Vues avancées et fragments (2/2)
Utilisation des fragments
– Cours 4 –
Chapitre 2 : Vues avancées et fragments (2/2)
Utilisation des fragments
Etudiants concernés
Faculté/Institut Département Niveau Spécialité
Prérequis
Gestion des vues et des layouts
Gestion des évènements
Objectifs du cours
Créer un Drawer et manipuler des fragments
Organiser une activité dans un TabLayout
Méthodes callback :
onAttach() : (quand le fragment est associé à
une activity) pour récupérer l’activité
contenante
onCreate() : pour instancier les objets non
graphiques
onCreateView() : pour instancier les objets
graphiques
onStart() : pour lancer les traitements
onResume() : pour s'abonner aux évènements
et récupérer le contexte
…
Méthodes callback :
…
onPause() : pour se désabonner aux
évènements et sauvegarder le contexte
onStop() : pour arrêter les traitements
(threads, …) et désallouer les ressources
onDestroyView() : pour libérer la mémoire
des objets graphiques
onDestroy() : (les ressources restants sont
libérées automatiquement)
onDetach() : (quand la vue associée au
fragment est détachée de l’activité)
/res/layout/fragment_my.xml
<LinearLayout xmlns:android="..." ...>
<!-- content -->
</LinearLayout>
/java/MyFragment.java
public class MyFragment extends Fragment{
public MyFragment(...){ ... }
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
...
return view;
}
}
getFragmentManager().beginTransaction()
.replace(R.id.container, new MyFragment())
.commit();
}
Le FragmentManager permet de :
Manipuler des fragments existants en utilisant findFragmentById(…) ou
findFragmentByTag(…)
Gérer la pile accessible via le bouton "Back" :
Dépiler un fragment de la pile de fragments, avec la méthode popBackStack()
Associer un Listener aux changement dans la pile avec la méthode
addOnBackStackChangedListener(…)
/java/FirstFragment.java
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_first, container, false);
...
return rootView;
}
}
/res/layout/fragment_first.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
Bibliothèque :
com.android.support:appcompat-v7:26.+
com.android.support:design:26.+
Méthode 1 :
Project Structure > Modules > app
> Onglet Depenendencies
Méthode 2 :
Dans
/Gradle un script Gradle
Scripts/build.gradle (Module: app)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.+’
implementation 'com.android.support:design:26.+'
}
/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/slidingTL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed" /> // fixed or scrollable
<android.support.v4.view.ViewPager
android:id="@+id/pagesVP"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
/java/MyPagerAdapter.java
public class MyPagerAdapter extends FragmentPagerAdapter {
private Context ctx;
public MyPagerAdapter(Context ctx, FragmentManager fm){super(fm); this.ctx=ctx;}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new FirstFragment();
case 1: ... }
}
@Override
public CharSequence getPageTitle(int position){
switch (position) {
case 0: return ctx.getString(R.string.first_title);
case 1: ... }
}
@Override
public int getCount() { return [NUMBER_OF_TAB]; }
}
/java/MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter adapter =
new MyPagerAdapter(this, getSupportFragmentManager());
pagesVP.setAdapter(adapter);
slidingTL.setupWithViewPager(pagesVP);
}
}
/java/FirstFragment.java
public class FirstFragment extends Fragment{
...
public FirstFragment(){ ... }
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("First title");
View rootView=inflater.inflate(R.layout.fragment_first, container, false);
...
return rootView;
}
}
/res/layout/fragment_first.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
/res/menu/nav_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/nav_first"
android:icon="@drawable/ic_menu_first"
android:title="@string/first_item" />
<item
android:id="@+id/nav_second"
android:icon="@drawable/ic_menu_second"
android:title="@string/second_item" />
...
</menu>
/res/layout/nav_header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
/res/layout/activity_main.xml
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer" ... >
<FrameLayout
android:id="@+id/contentFL"
android:layout_width="match..."
android:layout_height="match..." />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap..."
android:layout_height="match..."
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
/java/MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
NavigationView nav = (NavigationView) findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle =
new ActionBarDrawerToggle(this, drawer, "Open", "Close");
drawer.setDrawerListener(toggle); toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
...
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
return toggle.onOptionsItemSelected(item);
}
}
/java/MainActivity.java
public class MainActivity extends AppCompatActivity implements
implements NavigationView.OnNavigationItemSelectedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
...
FragmentManager fm = getSupportFragmentManager();
nav.setNavigationItemSelectedListener(this);
nav.getMenu().performIdentifierAction(R.id.nav_first, 0);
}
@Override
public boolean onNavigationItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.nav_first:
fm.beginTransaction().replace(R.id.contentFL, new FirstFragment()).commit();
case R.id.nav_second: ...
drawer.closeDrawers();
return true;
}
}
Challenges
Création d’un DrawerLayout avec un
menu : Map List
Challenges (ChallengesFragment) Challenges
Création d’un TabLayout associé à un
ViewPager :
Map (MapChallengesFragment)
List (ListChallengesFragment)
…
My challenges,
My friends,
Settings,
Disconnect,
…
Challenges fragment_challenges.xml
(dans contentFL)
Map List
Challenges
fragment_challenges_lis fragment_challenges_map
t.xml .xml
Rendus du TP 2 :
Avant le Samedi 4 décembre à 23h59
À : ac.chaouche@misc-umc.org
Objectifs :
Afficher une carte OSM et créer des marqueurs
Se géolocaliser et naviguer à travers la carte
Récupérer des routes à partir d’un serveur (mapquest, …)