首页 > 解决方案 > 通过父活动级别按钮在片段之间导航

问题描述

我希望能够通过在父 Activity 中设置的 Button OnClickLister 打开我的 CartFragment(所有片段具有相同的父 Activity,并且 navGraph 已连接并使用导航组件 XML 文件中的所有片段)但我不知道如何在使用导航组件时。我有几个小时的研究无济于事。

我的意图是在使用导航组件时导航到另一个片段,但我不知道如何创建在活动到片段之间移动的操作。 在此处输入图像描述

这是我的 MainActivity 布局:

<layout 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">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <!--    android:paddingTop="?attr/actionBarSize"-->

         
            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_cart_button"
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:drawableLeft="@drawable/ic_smart_cart_new_icon"
                android:text="Ir al carrito"
                android:textSize="16sp"
                android:visibility="visible"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent" />


            <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_constraintBottom_toTopOf="parent"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.001"
                app:navGraph="@navigation/mobile_navigation" />


        </androidx.constraintlayout.widget.ConstraintLayout>
    </FrameLayout>
</layout>

标签: androidkotlinandroid-architecture-navigation

解决方案


推荐阅读