Reemplazar un fragmento por otro fragmento

Quiero reemplazar un antiguo Fragment con un nuevo Fragment , pero sigo recibiendo los botones del antiguo Fragment que todavía es visible en el nuevo fragmento.

En el antiguo, en un clic de botón Introduzca aquí la descripción de la imagen

 FragmentTransaction transaction = getFragmentManager().beginTransaction(); Fragment newFragment = GenericMood.newInstance("a","b"); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack if needed transaction.replace(R.id.allmoods, newFragment); transaction.addToBackStack(null); transaction.commitAllowingStateLoss(); 

Puedo reemplazar el antiguo Fragment por el nuevo, pero los botones de R.id.allmoods Fragment siguen visibles en la parte superior del nuevo Fragment .

Introduzca aquí la descripción de la imagen

He intentado con este código dado a continuación.

 FragmentTransaction transaction = getFragmentManager().beginTransaction(); Fragment newFragment = GenericMood.newInstance("a","b"); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack if needed transaction.replace(((ViewGroup)getView().getParent()).getId(), newFragment); transaction.addToBackStack(null); transaction.commitAllowingStateLoss(); 

Archivos XML:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/allmoods" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimary" tools:context="com.moodoff.Moods"> <Button android:text="Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:id="@+id/btn_btn" android:height="80dp" android:width="100dp" android:onClick="putmeoff" android:layout_marginLeft="17dp" android:layout_marginStart="17dp"/> </RelativeLayout> 

Este es el fragmento que se supone que sustituye a lo anterior:

 <FrameLayout 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:id="@+id/genericmood" android:layout_height="match_parent" android:background="@color/colorPrimary" tools:context="com.moodoff.GenericMood"> <!-- TODO: Update blank fragment layout --> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#000000" android:layout_gravity="fill_horizontal" android:id="@+id/floatingButtons" > <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:layout_marginRight="14dp" app:backgroundTint="#ffffff" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:src="@drawable/cameraicon" android:id="@+id/btn_camera" app:fabSize="mini" /> </RelativeLayout> </FrameLayout> 

Ambos no funcionan. ¿Qué hacer? ACTUALIZACIÓN: Después de reemplazar con el contenedor adecuado los botones habían desaparecido pero el nuevo fragmento no se instanciaba correctamente. Tengo una pantalla en blanco puro. Introduzca aquí la descripción de la imagen

 my activity_alltabs.xml looks like this: <?xml version="1.0" encoding="utf-8"?> <android.support.design.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:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.moodoff.AllTabs"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/background_dark" /> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> 

He trabajado en fragmentos antes y espero que esto te ayude y te dé una mejor comprensión del flujo. En primer lugar, su archivo MainActivity.xml se verá así:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.activity.HomeActivity"> //This frameLayout will contain all your fragments view. <FrameLayout android:id="@+id/container_view" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </RelativeLayout> 

A continuación, crea dos fragmentos y su XML se menciona a continuación: fragment1.xml

 <RelativeLayout 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" android:clickable="true" // important to have this tools:context=".fragments.frament1"> <Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom"/> </RelativeLayout> 

El siguiente fragmento se vería exactamente igual al mencionado anteriormente. Aquí está el Fragment1.class :

 public class Fragment1 extends Fragment implements View.OnClickListener { Button btn; public Fragment1() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, container, false); view.setBackgroundColor(Color.WHITE); //Perform required conditions and return view button = (Button) view.findViewById(R.id.btn); button.setOnClickListener(this); return view; } public void onClick(View v) { switch(v.getId()) { case R.id.btn: //replace current fragment on button click Fragment fragment2= new Fragment2(); getFragmentManager().beginTransaction(). replace(R.id.container_view, fragment2). addToBackStack("frags").commit(); break; } } } 

Y el Fragmento2 sería como sigue:

  public class Fragment2 extends Fragment{ String TAG = "Fragment2"; public Fragment2() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment2,container,false); view.setBackgroundColor(Color.WHITE); return view; } } 

Como mencioné anteriormente, el archivo xml sería el mismo que fragment1.xml . Lo que es más importante aquí es que la actividad principal contendrá un diseño que tomará la vista de fragmentos cuando el usuario cambie fragmentos. Por lo tanto, utilizamos el método replace que simplemente reemplazaría la vista anterior por la vista de fragmentos especificada por nosotros.

Para entender el flujo de la transición del fragmento, en primer lugar, usted tiene que saber acerca de su estructura en la actividad. Veamos: a) Actividad: En el fondo de todo (MainActivity)

Activity_main.xml: –

 <RelativeLayout 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"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> 

Aquí @ + id / container es el diseño de lo que hacemos transiciones de los contenidos de los fragmentos.

B) FragmentA: Se agregó inicialmente fragmento al contenedor de MainActivity.

 FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); //Instance of fragment Fragment newFragment = FragmentA.newInstance("a","b"); //It will replace the fragment content view to container of main activity ft.replace(R.id.container, newFragment); //FragmentA is added to back stack with it's name as a tag ft.addToBackStack(FragmentA.class.getSimpleName()); ft.commitAllowingStateLoss(); 

B) FragmentB: Reemplazar FragmentA con FragmentB

 FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); //Instance of fragment Fragment newFragment = FragmentB.newInstance("a","b"); //It will replace the fragment content view to container of fragment A which // is previously replaced to main activity container ft.replace(R.id.container, newFragment); //FragmentB is added to back stack with it's name as a tag ft.addToBackStack(FragmentB.class.getSimpleName()); ft.commitAllowingStateLoss(); 

Lo principal detrás de esto es reemplazar / agregar la vista de contenido de fragmentos a la vista de contenedor de actividad.

En la función onCreate de su actividad, debería llamar a setContentView(R.layout.main) , y cuando quiera cargar un fragmento, debe elegir un ViewParent dentro de R.layout.main . El fragmento se convertirá en el hijo de ese ViewParent. Así que la identificación pasó a FragmentTransaction.replace , es el id del ViewParent en R.layout.main .

Tiene sentido que el botón en su allmoods RelativeLayout permanecerá porque la función FragmentTransaction.replace sólo reemplaza un fragmento existente que está en ese contenedor. Todo en R.layout.main permanecerá. Así es como una actividad mantiene contenido estático, como cajones o barras de herramientas.

Cuando cargues tu "nuevo fragmento" usarás el mismo id. Así que el "nuevo fragmento" reemplaza el "fragmento antiguo" como el nuevo hijo del ViewParent dentro de R.layout.main .

Aquí está la guía de la API Fragmentos .

Actualizar:

Cuando llama a FragmentTransaction.replace en la función onCreate de su actividad, esto podría recrear un Fragmento existente. Asegúrese de que savedInstanceState (el paquete pasado en onCreate) es nulo. Si el savedInstanceState no es nulo, entonces el fragmento probablemente ya existe y puede encontrarlo así;

 Fragment f = getFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG); 

Actualización 2:

Aquí hay una guía que debe ayudarle. Parece que podría utilizar FragmentPagerAdapter para simplificar las transacciones de fragmentos.

Intente esto una vez, 1. si usted está pasando cualquier valor sobre botón haga clic en Actividad

 Category category=new Category(); Bundle bundle=new Bundle(); bundle.putString("heading",heading); bundle.putInt("position",position1+1); bundle.putString("url",url); bundle.putString("sku",sku); bundle.putBoolean("flag",flag); category.setArguments(bundle); FragmentManager fragmentManager = getSupportFragmentManager(); final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragmentCategories,category); fragmentTransaction.commit(); 

En fragmento

 Bundle bundle=getArguments(); if(getArguments()!=null) { position = bundle.getInt("position"); heading = bundle.getString("heading"); url = bundle.getString("url"); sku=bundle.getString("sku"); flag=bundle.getBoolean("flag"); tvHeading.setText(heading); video_chapter = handler.getContent_Aspects(position); adapter = new Chapter_content_Adapter(getActivity(), video_chapter, url, heading, position); gvChapter.setAdapter(adapter); } 

2.if simplemente llamando fragmento

 FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentCategories=fragmentManager.findFragmentById(R.id.fragmentCategories); fragmentTransaction.commit(); 

Pruebe el siguiente código.

A) Crear actividad como sigue:

Actividad principal

 import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements ShowNextFragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fragmentA=new FragmentA(); FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.container,fragmentA); fragmentTransaction.addToBackStack("A"); fragmentTransaction.commitAllowingStateLoss(); } @Override public void showFragment() { FragmentB fragmentB=new FragmentB(); FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.container,fragmentB); fragmentTransaction.addToBackStack("B"); fragmentTransaction.commitAllowingStateLoss(); } } 

B) Crear 2 fragmentos de la siguiente manera:

Fragmento A

  import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentA extends Fragment { private ShowNextFragment showNextFragment; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { showNextFragment=(ShowNextFragment)getActivity(); Log.e("CAllback","Set"); }catch (ClassCastException e){ Log.e("Error","Please Implement ShowFragment Interface"); } return inflater.inflate(R.layout.fragment_a,container,false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (showNextFragment!=null){ showNextFragment.showFragment(); } } }); } } 

Fragmento B

 import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentB extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_b,container,false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } } 

C) Crear una interfaz de la siguiente manera

 public interface ShowNextFragment { void showFragment(); } 

D) crear siguientes xmls como:

I) activity_main

  <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" > </RelativeLayout> 

Ii) fragmento_a

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorcyan" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Fragment B" /> </LinearLayout> 

Iii) fragmento_b

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorgreen" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fragment B" android:layout_centerVertical="true" android:layout_alignRight="@+id/btn_camera" android:layout_alignEnd="@+id/btn_camera" /> <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" app:backgroundTint="#ffffff" android:src="@android:drawable/ic_dialog_email" android:id="@+id/btn_camera" app:fabSize="mini" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout> 

El problema era que el ID de contenedor que pasaba al método replace era el ID del fragmento que estaba reemplazando, no el ID del contenedor de fragmentos. Esto parece explicar por qué algunos de los controles de fragmentos originales se quedaron después de la sustitución – que fragmento entero no fue reemplazado.

¡Modifíquelo para obtener el ID de la vista de contenedor de fragmentos y funcionará! Aquí está el código:

Transaction.replace ((ViewGroup) (getView (). GetParent ())). GetId (), fragmento);

Encontré la respuesta para obtener el ID de la vista de contenedor de un fragmento aquí, Obtener el fragmento de la identificación de contenedor.

Simplemente haga que los botones setVisibility (View.GONE) en su actividad cuando ese fragmento es comenzar la transacción.

  • Arregle dinámicamente los botones alrededor de un círculo
  • Cómo añadir una barra de acción a la plantilla de actividad de Google Maps predeterminada en Android Studio
  • Obtener la altura del teclado de software de Android sin ajustar "adjustResize"
  • ¿Cómo aumentar el espacio entre texto y subrayado en TextView Android?
  • Mapview y Fragmento
  • Descartar actividad en android
  • Android: Usar el estilo predeterminado en un título de diálogo personalizado
  • Mostrar barra de pestañas y listIn Actionbar al mismo tiempo. (Android Honeycomb)
  • Menú emergente expandir / contraer desde un icono en la barra de acciones
  • Obtener el tamaño de un texto en TextView
  • Actividad con un fondo transparente
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.