0

Tengo una aplicación en que tiene una barra de menú abajo, de uno de los fragments, quiero pasar a otro que yo he hecho, el problema es que se sigue viendo la lista del fragment anterior.

Este es mi MainActivity:

public class MainActivity extends AppCompatActivity{



  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      BottomNavigationView navView = findViewById(R.id.nav_view);
      // Passing each menu ID as a set of Ids because each
      // menu should be considered as top level destinations.
      AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
              R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
              .build();
      NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
      NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
      NavigationUI.setupWithNavController(navView, navController);


  }


}

el layout de Activity Main (activity_main)

<?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/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <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="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation"
    />




</androidx.constraintlayout.widget.ConstraintLayout>

Este es el fragmento que sale primero, Home Fragment:


public class HomeFragment extends Fragment implements DBInterface, RecordListAdapter.MyViewHolder.onRecordListener {
    private User actual_user = User.getUser();
    //private HomeViewModel homeViewModel;

    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;
    private JSONArray results;
    private RecordListAdapter.MyViewHolder.onRecordListener listener;

    private View root;

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

        root = inflater.inflate(R.layout.fragment_home, container, false);


        getList();
        if(results != null)
            mAdapter.notifyDataSetChanged();

        return root;
    }



    public void getList(){
        //Date currentDate = new Date(System.currentTimeMillis());
        JSONObject params = new JSONObject();
        try {
            params.put("email", actual_user.getEmail() );
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(params != null){
            DBAccess.getRecords(getContext(), this, params);
        }
        else{
            Toast.makeText(getContext(), "Error" + "Ha ocurrido un error", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        //Toast.makeText(this, "Error" + error, Toast.LENGTH_SHORT).show();
        Log.d("response","error" + error.toString());
    }

    @Override
    public void onResponse(JSONObject response) {
        try {
            if (response.has("type")) {
                if("RECORD".equals(response.getString("type"))){
                    Log.d("response","records list");
                    //Show all the records
                    int num = response.length();
                    //if(num > 1){
                        results = response.getJSONArray("Results");
                        /*for (int i = 0; i < results.length(); i++){
                            JSONObject aux = results.getJSONObject(i);
                            Log.d("response","ID" + aux.get("ID"));
                        }*/

                    recyclerView = (RecyclerView)  getView().findViewById(R.id.list_Records_today);
                    //We create the adapter

                    recyclerView.setHasFixedSize(true);
                    layoutManager = new LinearLayoutManager(getContext());
                    ((LinearLayoutManager) layoutManager).setOrientation(LinearLayoutManager.VERTICAL);
                    recyclerView.setLayoutManager(layoutManager);

                    // specify an adapter
                        mAdapter = new RecordListAdapter(results, this);
                        recyclerView.setAdapter(mAdapter);

                        DividerItemDecoration divider = new DividerItemDecoration(getContext(), ((LinearLayoutManager) layoutManager).getOrientation());
                        recyclerView.addItemDecoration(divider);

                        Log.d("response","fin");
                    //}
                    /*else{
                        //there is only one show the only one
                        Log.d("response","solo uno");
                    }*/

                }
                else{
                    //there is not records
                    Toast.makeText(getContext(), "No registros",Toast.LENGTH_LONG).show();
                }
            }
            else{
                Log.d("response","error param");
                if (response.has("ERROR")) {
                    Toast.makeText(getContext(), response.getString("ERROR"),Toast.LENGTH_LONG).show();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRecordItemClick(int position) {
        try {
            int id = getID(position);
            // Create fragment and give it an argument specifying the article it should show
            //RecordView newFragment = new RecordView(getID(position),getName(position),getDate(position),getTime(position));
            RecordView newFragment = new RecordView();
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            //transaction.replace(R.id.nav_host_fragment, newFragment);
            transaction.replace(this.getId(), newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Su layout (fragment_home)

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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list_Records_today"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

Y al fragment que quiero pasar, al tocar uno de los items de la lista:


public class RecordView extends Fragment {

    private int ID;
    private String date, time,name;
    /*public RecordView(int ID,String name, String date,String time) {
        this.ID = ID;
        this.date = date;
        this.time = time;
        this.name = name;
    }*/
    public RecordView(){}

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_record_view, container, false);
        TextView name_item = root.findViewById(R.id.record_view_name);
        name_item.setText("HELLOUUUU");
        return root;
    }
}

Su layout (fragment_record_view)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecordView">

    <TextView
        android:id="@+id/record_view_name"
        android:layout_width="150dp"
        android:layout_height="90dp"
        android:text="TextView"
        android:textAlignment="textEnd" />
</FrameLayout>

El resultado es que se ve a la vez la lista y el texto diciendo "Hellou". ¿Alguien me puede ayudar?

Muchas gracias y un saludo

1 respuesta 1

1

Hay algo muy importante que dese saber acerca de los Fragments y es que solo se pueden reemplazar aquellos que se han agregado dinamicamnente usando código en un contenedor mediante FragmentTransaction.

Por lo tanto primeramente tienes que agregar el Fragment y posteriormente este se puede reemplazar, ejemplo:

FragmentEjemplo fragment = new FragmentEjemplo ();
fragmentTransaction.add(R.id.nav_host_fragment, fragment, "nombreFragment");  
fragmentTransaction.commit();

En tu caso ya estas definiendo un Fragment , por esta razón este no se esta reemplazando:

<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="@id/nav_view"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navG 
2
  • He hecho esto transaction.add(R.id.nav_host_fragment, newFragment, "nombreFragment"); transaction.commit(); transaction.replace(R.id.nav_host_fragment, newFragment); Pero sigue sin funcionar :(
    – Monetillo
    Commented el 26 may. 2020 a las 14:24
  • Vale lo que pasaba es que con el al haber hecho la aplicación con la barra de navegación abajo, hay que navegar con el nav View.
    – Monetillo
    Commented el 30 may. 2020 a las 11:18

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

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