Загрузить фрагмент в навигацию программно - PullRequest
0 голосов
/ 11 октября 2019

Я создал новый проект из шаблона действий навигатора в Android Studio, и у меня есть следующие XML-файлы:

content_main.xml

<androidx.constraintlayout.widget.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_shopping_list">

    <fragment
        android:id="@+id/nav_products_list"
        android:name="com.example.producttracker.ui.products_list.ProductsListFragment"
        android:label="@string/menu_products_list"
        tools:layout="@layout/fragment_products_list" />

</navigation>

Проблема в том, что когда у меня во фрагменте product_list есть кнопка, которая при нажатии должна загрузить новый фрагмент, заменяющий текущий. Однако в данный момент он просто загружает новый фрагмент поверх существующего.

код, используемый для загрузки нового фрагмента:

                AppCompatActivity activity = (AppCompatActivity) view.getContext();

                Fragment inputFragment = new ProductInputFragment();


                FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.nav_host_fragment, inputFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();

Насколько я понимаю, причина в том, чтоФрагмент product_list не добавляется программно, поэтому его нельзя заменить FragmentManager. Если это так, как я могу загрузить этот фрагмент программно? Я прочитал сотни статей, но я все еще в замешательстве, потому что в моем случае это связано с навигацией.

Ответы [ 3 ]

0 голосов
/ 12 октября 2019

Я решил проблему, избавившись от FragmentTransaction s и определив все мои фрагменты как пункты назначения для моей навигации. Этот урок был полезен:

https://developer.android.com/guide/navigation/navigation-getting-started

0 голосов
/ 12 октября 2019
Simply use Fragment manager to change the fragment.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = 
getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

//   Commit the transaction
transaction.commit();
0 голосов
/ 11 октября 2019

У меня есть хакерское решение для вас:

Добавьте контейнер в макет, скрыть и показать фрагмент и контейнер в зависимости от ваших требований.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...