0

Tengo un problema al momento de realizar la transacción de fragmentos en una actividad Tengo el diseño de mi navegación en mi carpeta navigation:

auth_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
    tools:context=".Activities.AuthActivity">

    <fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/auth_navigation" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

El detalle es que normal llego al siguiente fragmento:

register_code_fragment.xml

<?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"
    tools:context=".Fragments.Auth.register_code_fragment">

    <ImageView
        android:id="@+id/tw_img_back3"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_gravity="left"
        android:layout_marginStart="15dp"
        android:layout_marginTop="18dp"
        android:src="@drawable/back_arrow"
        android:visibility="visible"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="15dp"
        android:text="Ingrese el código:"
        android:textColor="@color/black1"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tw_img_back3" />

    <EditText
        android:id="@+id/codeRegEditText"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="20dp"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Código"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/btnCodeValidationRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:layout_marginStart="15dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="15dp"
        android:background="@color/black1"
        android:text="Siguiente"
        android:textColor="@color/White"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.468"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/codeRegEditText" />


</androidx.constraintlayout.widget.ConstraintLayout>

Estoy pasando con normalidad el email al siguiente fragmento con bundle:

register_form_fragment

<?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"
    tools:context=".register_form_fragment">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:scrollbars="none">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:scrollbars="vertical"
            android:paddingBottom="30dp">

            <ImageView
                android:id="@+id/tw_img_back4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_gravity="left"
                android:layout_marginStart="15dp"
                android:layout_marginTop="18dp"
                android:src="@drawable/back_arrow"
                android:visibility="visible"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/ftvg_txt_nombre_user"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                android:text="Registro"
                android:textColor="#000000"
                android:textSize="30dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tw_img_back4"
                tools:ignore="MissingConstraints" />

            <!--Aqui va el primer EditText-->

            <EditText
                android:id="@+id/register_edit_text_correo"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                android:ems="10"
                android:hint="ejemplo@ejemplo.com"
                android:enabled="false"
                android:textStyle="bold"
                android:textColor="@color/black1"
                android:inputType="textEmailAddress"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/ftvg_txt_nombre_user" />

            <EditText
                android:id="@+id/register_edit_text_nombre"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="7dp"
                android:ems="10"
                android:hint="Nombres"
                android:inputType="text"
                app:layout_constraintEnd_toStartOf="@+id/guideline7"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/register_edit_text_correo" />

            <EditText
                android:id="@+id/register_edit_text_apellido"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"

                android:layout_marginStart="7dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                android:ems="10"
                android:hint="Apellidos"
                android:inputType="text"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@+id/guideline7"
                app:layout_constraintTop_toBottomOf="@+id/register_edit_text_correo" />

                <EditText
                    android:id="@+id/register_edit_text_contraseña"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:ems="10"
                    android:hint="Contraseña"
                    android:inputType="textPassword" />

            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/register_text_layout3"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"

                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/register_text_layout">

                <EditText
                    android:id="@+id/register_code_referencial"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="Código(Opcional)" />

            </com.google.android.material.textfield.TextInputLayout>

            <Button
                android:id="@+id/btnRegistrarUser"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:textAllCaps="false"
                android:textSize="20dp"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                android:background="@color/black1"
                android:text="Siguiente"
                android:textStyle="bold"
                android:textColor="@android:color/white"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/linearLayout1" />

            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="15dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/register_text_layout3">

                <TextView
                    android:id="@+id/txt_view_terminos"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:text="terminos y condiciones"
                    android:textColor="@color/black1"
                    android:textSize="12dp"
                    android:textStyle="bold" />

            </LinearLayout>

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintGuide_percent="0.5" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

Mi problema es que cuando realizo la transacción de la siguiente manera normal capturo el valor del bundle pero se anteponen los fragmentos el fragmeto register_form_fragment.xml esta encima del fragmento register_code_fragment.xml, traté de que en auth_navigation.xml en vez de la etiqueta cambiarlo a pero me envia un error ya que estoy trabajando con lo nuevo de android Navigation component y no me reconoce los atributos de app:defaultNavHost="true" y app:navGraph="@navigation/auth_navigation"

Código de la transacción:

val bundleEmail = Bundle()
bundleEmail.putString("emailVerificate", email)

val newFragment:register_form_fragment = register_form_fragment()
newFragment.arguments = bundleEmail

val transaction = requireActivity().supportFragmentManager.beginTransaction().apply {
                            replace(R.id.fragment, newFragment)
                        }
transaction.commit()

Si alguien podría ayudarme o guiarme se le agradezco de antemano

1 respuesta 1

1

Si estas utilizando navigation Components de Android podrías realizar lo siguiente:

1.- El código que se muestra a continuación entiendo que es el activity.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
tools:context=".Activities.AuthActivity">

<fragment
    android:id="@+id/fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/auth_navigation" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Es decir que tu activity contiene un <fragment> donde vamos a poner nuestros fragments. según el código este xml debería llamarse activity_auth. Dado que pertenece al activity AuthActivity.

Ahora como vemos en app:navGraph="@navigation/auth_navigation", contiene un navGraph. Entonces debemos crear el recurso auth_navigation dentro de la carpeta navigation.

2.- Se tiene el archivo auth_navigation que indica como navegas entre tus fragments, como vemos las acciones son refrelajadas como action que indican que se puede ir de un fragment hacia otro.

<?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"
android:id="@+id/nav_graph_payment_cards"
app:startDestination="@id/registerCodeFragment">

<fragment
    android:id="@+id/registerCodeFragment"
    android:name="{PACKAGE_NAME}.RegisterCodeFragment"
    android:label="RegisterCodeFragment">
    
    <action
        android:id="@+id/action_registerCodeFragment_to_registerFormFragment"
        app:destination="@id/registerFormFragment"
        app:popUpTo="@+id/registerFormFragment"
        app:popUpToInclusive="true" />
        
</fragment>

<fragment
    android:id="@+id/registerFormFragment"
    android:name="{PACKAGE_NAME}.RegisterFormFragment"
    android:label="RegisterFormFragment">

    <argument
        android:name="email"
        app:argType="string"/>

</fragment>

En donde dice {PACKAGE_NAME} reemplazalo por el packageName que tienes. Suponiendo que la ruta de mi fragment es com.rguzman.android.login.LoginFragment entonces quedaría android:name="com.rguzman.android.login.RegisterFormFragment"

Ahora que tenemos definido el navGraph podemos observar un parámetro importarte dentro del action.

3.- Puede que tengas dos maneras que quieras navegar. Trataré de explicar las dos maneras

  • Imaginemos que queremos ir de registerCodeFragment hacia registerFormFragment. Luego de hacer el cambio **Queremos hacer back o que se agregue al stack ** nuestra nueva fragment registerFormFragment.Es decir en la base tenemos a registerCodeFragment y luego tenemos registerFormFragment.

Para hacer esto tenemos que quitar estos dos parámetros de nuestro action:

<action
...
        app:popUpTo="@+id/registerFormFragment"
        app:popUpToInclusive="true" />

con lo cual nos quedaria

<action
    android:id="@+id/action_registerCodeFragment_to_registerFormFragment"
    app:destination="@id/registerFormFragment"/>

y para navegar simplemente llamamos a nuestro controller y le indicamos el action

findNavController().navigate(R.id.action_registerCodeFragment_to_registerFormFragment)
  • Ahora el segundo caso es cuando queremos ir de registerCodeFragment hacia registerFormFragment. Luego de hacer el cambio No queremos que al hacer back o se agregue al stack nuestra nueva fragment registerFormFragment.Es decir en la base tenemos a registerCodeFragment y luegoreemplazamos este fragment con registerFormFragment. Por lo tanto solo tendríamos un fragment.

Para esto no debemos eliminar nada del ejemplo. Es decir nos quedamos con :

<action
        android:id="@+id/action_registerCodeFragment_to_registerFormFragment"
        app:destination="@id/registerFormFragment"
        app:popUpTo="@+id/registerFormFragment"
        app:popUpToInclusive="true" />

Los dos parámetros importantes son app:popUpTo y app:popUpToInclusive que nos ayudaran a remover el fragment y reemplazarlo.

para navegar lo hacemos de la misma manera.

findNavController().navigate(R.id.action_registerCodeFragment_to_registerFormFragment)

Finalmente como quieres pasar datos desde un fragment a otro, navigation components nos provee de <argument/> donde le indicamos el tipo y el nombre

entonces para pasar tu argument de un Fragment a otro, en este caso le pasamos un action pero creado con tus parámetros. Por ejemplo:

val email = "email"
val action = RegisterFormFragmentDirections.actionRegisterCodeFragmentToRegisterFormFragment(email)

findNavController().navigate(action)

Finalmente en tu fragment registerFormFragment recibes el parámetros con navArgs y puedes utilizarlo.

Espero te ayude :)

Referencias

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.