0

Estoy trabajando con Navigation Drawer y tengo problemas al querer pasar de un fragment a otro mediante un boton desde la clase HomeFragment.java

Es decir, en el xml de la clase HomeFragment tengo algunos elementos, entre ellos un boton llamado img_btn_1 en el que quiero añadirle como evento un paso a un fragment blank, pero no me funciona, la app se abre pero no ejecuta el evento.

esto es lo que tengo:

    public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // el objeto root es de tipo vista, nos permite instanciar los elementos xml
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_facul, container, false);


        final TextView textView = root.findViewById(R.id.text_home);
        final ImageButton img_btn_1 = root.findViewById(R.id.img_btn_1);
        final ImageButton img_btn_2 = root.findViewById(R.id.img_btn_2);
        final ImageButton img_btn_3 = root.findViewById(R.id.img_btn_3);
        final ImageButton img_btn_4 = root.findViewById(R.id.img_btn_4);
        final ImageButton img_btn_5 = root.findViewById(R.id.img_btn_5);

        final YouTubePlayerView youTubePlayerView = root.findViewById(R.id.youtube_player_view);

        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);

                getLifecycle().addObserver(youTubePlayerView);

                //EVENTOS DE CADA BOTON

                img_btn_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        FragmentManager manager = getActivity().getSupportFragmentManager();
                        Fragment1_btn1 fragment1 = new Fragment1_btn1();
                        manager.beginTransaction()
                                .setCustomAnimations(R.anim.enter_rigth_to_left, 
                                        R.anim.exit_rigth_to_left,
                                        R.anim.enter_left_to_rigth, R.anim.exit_left_to_rigth)
                                .replace(R.id.frame1, fragment1)
                                .addToBackStack(null)
                                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                                .commit();

                    }
                });

        });
        return root;
    }

}

pero no me toma el evento del boton, en la linea .replace(R.id.frame, fragment1) le puse como nombre "frame" al frame del layout xml que conecta la clase HomeFragment, y ese "frame" lo tengo dentro de un constraint layout:

    <?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:id="@+id/constlay1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <FrameLayout
        android:id="@+id/frame_container1"
        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"
        app:layout_constraintVertical_bias="0.016">

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/LinearL_Player"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
                    android:id="@+id/youtube_player_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:autoPlay="true"
                    app:showFullScreenButton="true"
                    app:videoId="NuamcPG2AhQ" />

            </LinearLayout>


            <LinearLayout
                android:id="@+id/LinearL_btns1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/img_btn_1"
                    android:layout_width="180dp"
                    android:layout_height="60dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="20dp"
                    android:contentDescription="@string/description_btn"
                    android:scaleType="fitCenter"
                    android:src="@drawable/logo_select1" />

                <ImageButton
                    android:id="@+id/img_btn_2"
                    android:layout_width="180dp"
                    android:layout_height="60dp"
                    android:layout_marginTop="20dp"
                    android:contentDescription="@string/description_btn"
                    android:scaleType="fitCenter"
                    android:src="@drawable/logo_select2" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/LinearL_btns2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="-25dp"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/img_btn_3"
                    android:layout_width="180dp"
                    android:layout_height="60dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginLeft="55dp"
                    android:layout_marginTop="40dp"
                    android:layout_marginRight="55dp"
                    android:contentDescription="@string/description_btn"
                    android:scaleType="fitCenter"
                    android:src="@drawable/logo_select3" />

                <ImageButton
                    android:id="@+id/img_btn_4"
                    android:layout_width="180dp"
                    android:layout_height="60dp"
                    android:layout_marginTop="40dp"
                    android:contentDescription="@string/description_btn"
                    android:scaleType="fitCenter"
                    android:src="@drawable/logo_select4" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/LinearL_btns3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/img_btn_5"
                    android:layout_width="180dp"
                    android:layout_height="60dp"
                    android:layout_marginTop="20dp"
                    android:contentDescription="@string/description_btn"
                    android:scaleType="fitCenter"
                    android:src="@drawable/logo_select5" />

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

                    <TextView
                        android:id="@+id/text_home"
                        android:layout_width="161dp"
                        android:layout_height="35dp"
                        android:layout_marginTop="32dp" />
                </FrameLayout>

            </LinearLayout>

        </LinearLayout>
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Mi problema es que al darle click al boton img_btn_1 no me abre el fragment, no se si sea un error al momento de llamar el "frame" en la linea .replace(R.id.frame, fragment1) o si lo estoy haciendo mal al trabajar un fragment de un navegation drawer a otro fragment independiente.

2
  • android:id="@+id/frame_container1", es el mismo nombre "frame" que menciono, no sé que estoy haciendo mal que no me toma el evento el 14 sep. 2020 a las 18:37
  • en tu proyecto se generó la carpeta navigation en res? para navegar entre fragmentos pues usar FragmantTransaction ó Navigation: es.stackoverflow.com/questions/320804/…
    – armen
    el 16 sep. 2020 a las 15:54

1 respuesta 1

1

Quizás deberías sacar img_btn_1.setOnClickListener del método onChanged, ya que según lo tienes ahora solo estás asignando el ClickListener al botón si llega algún evento del homeViewModel.

En resumen. Tu código debería quedar así:

    public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // el objeto root es de tipo vista, nos permite instanciar los elementos xml
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_facul, container, false);


        final TextView textView = root.findViewById(R.id.text_home);
        final ImageButton img_btn_1 = root.findViewById(R.id.img_btn_1);
        final ImageButton img_btn_2 = root.findViewById(R.id.img_btn_2);
        final ImageButton img_btn_3 = root.findViewById(R.id.img_btn_3);
        final ImageButton img_btn_4 = root.findViewById(R.id.img_btn_4);
        final ImageButton img_btn_5 = root.findViewById(R.id.img_btn_5);

        final YouTubePlayerView youTubePlayerView = root.findViewById(R.id.youtube_player_view);

        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);

                getLifecycle().addObserver(youTubePlayerView);
        });

//EVENTOS DE CADA BOTON

        img_btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager manager = getActivity().getSupportFragmentManager();
                Fragment1_btn1 fragment1 = new Fragment1_btn1();
                manager.beginTransaction()
                        .setCustomAnimations(R.anim.enter_rigth_to_left, 
                                R.anim.exit_rigth_to_left,
                                R.anim.enter_left_to_rigth, R.anim.exit_left_to_rigth)
                        .replace(R.id.frame1, fragment1)
                        .addToBackStack(null)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .commit();
            }
        });
        return root;
    }

}
2
  • 1
    Gracias, pero mira que no me toma el .setOnClickListener, me lo marca en rojo, deberia añadirle algo al public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ? el 16 sep. 2020 a las 2:06
  • En principio no debería dar problema. ¿Qué error te marca?
    – JPery
    el 16 sep. 2020 a las 10:51

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.