Angenommen folgenden ist Ihre Aktivität Layout:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
Hier ist FrameLayout
mit ID fragment_container
Ihr Fragment-Container. Alle Fragmente werden in diesen Container geladen.
Dann in Ihrem MainActivity
‚s onCreate()
Methode, setzen Sie dieses Layout als content mit setContentView(R.layout.activity_main);
eine Instanz unseres Containerelement holen
FrameLayout fragmentContainer = (FrameLayout) findViewById(R.id.fragment_container);
Wenn Sie nun Fragment ändern müssen, Anruf diese Methode (platziert in MainActivity
):
public void changeFragment (Fragment fragment, String fragmentName) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(fragmentContainer, fragment);
fragmentTransaction.addToBackStack(fragmentName);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
Wenn Sie Unterstützung Fragmente verwenden Verwenden Sie aus der Support-Bibliothek getSupportFragmentManager()
anstelle von getFragmentManager()
Verwenden Sie eine Layout-Ansichtsgruppe als Container für Fragmente in Ihrer Aktivität, und fügen Sie Fragmente in diesem Container hinzu oder ersetzen Sie sie. Was hast du probiert? – rupinderjeet
Können Sie bitte ein wenig erklären, wie das geht. Ich bin völlig darin versunken, wirksame Wege zu finden, dies zu tun – Zoffa