Sobes.tech
Junior — Middle

Koje metode možete koristiti za kreiranje i prikazivanje Fragment u aplikaciji?

sobes.tech АИ

Одговор од АИ

Kreiranje i prikaz Fragment u Androidu može se realizovati na više načina:

  1. Dinamično dodavanje putem FragmentManager-a:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
transaction.add(R.id.container, fragment);
transaction.commit();
  1. Statično dodavanje u XML layout:
<fragment
    android:id="@+id/my_fragment"
    android:name="com.example.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. Zamena fragmenta:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, new MyFragment());
transaction.addToBackStack(null);
transaction.commit();

Izbor metode zavisi od zadatka: statička metoda je jednostavnija, ali manje fleksibilna; dinamička metoda omogućava upravljanje fragmentima tokom izvršenja.