Junior — Middle
Akými metódami je možné implementovať vytváranie a zobrazovanie Fragment v aplikácii?
sobes.tech AI
Odpoveď od AI
Vytváranie a zobrazovanie fragmentov v Androidu je možné realizovať niekoľkými spôsobmi:
- Dynamické pridanie pomocou FragmentManager:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
transaction.add(R.id.container, fragment);
transaction.commit();
- Statické pridanie v XML rozložení:
<fragment
android:id="@+id/my_fragment"
android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- Výměna fragmentu:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, new MyFragment());
transaction.addToBackStack(null);
transaction.commit();
Voľba metódy závisí od úlohy: statická metóda je jednoduchšia, ale menej flexibilná; dynamická metóda umožňuje spravovať fragmenty počas behu aplikácie.