Как закрыть родительский фрагмент от дочернего фрагмента в компоненте навигации - PullRequest
0 голосов
/ 04 января 2019

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

Я могу закрыть фрагмент, позвонив getActivity().getSupportFragmentManager().popBackStack(); с этим я могу только закрыть текущий верхний фрагмент в заднем стеке.

enter image description here

на этой картинке я хочу закрыть Fragment2 от Framgent3.

EDIT:

Я открываю Fragment2 с помощью: Navigation.findNavController(getView()).navigate(R.id.action_fragment1_to_fragment2);

Fragment1:

public class Fragment1 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_fragment1_to_fragment2);
            }
        });
    }
}

Макет Fragment1:

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="@color/colorPrimaryDark">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

Framgent2:

public class Fragment2 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public void close () {
        getActivity().getSupportFragmentManager().popBackStack();
    }
}

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <fragment
        android:id="@+id/child_graph_base"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/child_graph" />
</android.support.constraint.ConstraintLayout>

Fragment3:

public class Fragment3 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment3, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavHostFragment navHostFragment = (NavHostFragment) getParentFragment();
                Fragment2 fragment2 = (Fragment2) navHostFragment.getParentFragment();
                fragment2.close();
            }
        });
    }
}

Макет Fragment3:

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="@color/colorPrimaryDark">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Основной график (MainActivity): enter image description here

<?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/main_graph"
    app:startDestination="@id/fragment1">

    <fragment
        android:id="@+id/fragment1"
        android:name="alistar.navigation.fragments.Fragment1"
        android:label="fragment1"
        tools:layout="@layout/fragment1" >
        <action
            android:id="@+id/action_fragment1_to_fragment2"
            app:destination="@id/fragment2" />
    </fragment>
    <fragment
        android:id="@+id/fragment2"
        android:name="alistar.navigation.fragments.Fragment2"
        android:label="fragment2"
        tools:layout="@layout/fragment2" />
</navigation>

Детский график (в Framgent2)

enter image description here

<?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/child_graph"
    app:startDestination="@id/fragment3">

    <fragment
        android:id="@+id/fragment3"
        android:name="alistar.navigation.fragments.Fragment3"
        android:label="fragment3"
        tools:layout="@layout/fragment3" />
</navigation>

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Я решил проблему, вызвав метод close() в родительском фрагменте (Fragment2) из ​​Fragment3. я изменил метод закрытия на это:

public void close () {
    Navigation.findNavController(getView()).popBackStack();
}

также я удалил:

app:defaultNavHost="true"

из моего дочернего графа и работает нормально!

0 голосов
/ 04 января 2019

включить график (frag2, frag3) в график frag1, используя include

<include app:graph="@navigation/frag1_graph"/>

, а затем:

добавить действие к вашему фрагменту3 с соответствующими аргументами Destination и popUpTo

<fragment
    android:id="@+id/Fragment3"
    android:name="whatever"
    android:label="whatever"
    tools:layout="@layout/whatever" >
     <action
        android:id="@+id/action_Fragment3_to_Fragmen1"
        app:destination="@id/Fragment1"
        app:launchSingleTop="true"
       app:popUpTo="@+id/Fragment1"
       app:popUpToInclusive="true" /> </fragment>

, затем

findNavController(fragment).navigate(R.id.action_Fragment3_to_fragment1)

, а затем снова отобразите фрагмент3.я думаю, это то, что вы хотите, верно?

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