Cómo implementar mostrar y ocultar fragmento dentro de fragmento en android
¿Cómo implementar mostrar y ocultar fragmento dentro de fragmento en Android? He añadido dos fragmentos dentro de la actividad. Un fragmento que contiene el menú y un fragmento contienen submenú. Tengo mucho botón en el fragmento de menú como casa, idea, etc .. Si hago clic en botón de idea. Tengo que mostrar el submenú. Si vuelvo a hacer clic en el botón de idea, tengo que ocultar el submenú. ¿Puede alguien dar ejemplo, o cómo acceder a un fragmento de vista en otro fragmento?
Este es mi layout principal
- Android API TabActivity deprecation
- Cargar archivo de texto en webview android
- La aplicación se bloquea en rotación sin stackTrace
- Fragmento de Android ver estado dentro de una pestaña de host
- Animación de fragmentos y la pila trasera
?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment class="com.gcm.fragment.CommonFragment" android:id="@+id/the_frag" android:layout_width="wrap_content" android:layout_height="match_parent" /> <fragment class="com.gcm.fragment.SubFragment" android:id="@+id/the_frag1" android:layout_marginTop="130dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
En mi fragmento
package com.gcm.fragment; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.TextView; public class CommonFragment extends Fragment implements OnClickListener { TextView txtIhaveIdea=null; boolean menuVisible=false; public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.collapsed_menu2, container, false); txtIhaveIdea=(TextView)layout.findViewById(R.id.txtIhaveAnIdea); txtIhaveIdea.setOnClickListener(this); return layout; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(!menuVisible) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); fm.beginTransaction(); Fragment fragOne = new SubFragment(); ft.show(fragOne); } else { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); fm.beginTransaction(); Fragment fragOne = new SubFragment(); ft.hide(fragOne); } } }
Gracias
- Cómo Estilo un FragmentTabHost dentro de un fragmento
- Circular ViewPager que utiliza FragmentPagerAdapter
- Mi aplicación se bloquea en modo horizontal
- Cómo cambiar fragmento de forma programática en FragmentPagerAdapter?
- Android: navegar hasta la actividad principal recrea la actividad principal
- Borrar la pila trasera usando fragmentos
- Fragmento en la ronda Desgaste reloj girando en negro en el emulador / reloj
- Android - después del cambio de orrientación cambia el fragmento objetivo en el fragmento de diálogo
Teniendo en cuenta esta pregunta tiene más de 2K .. una respuesta todavía puede ayudar a los nuevos lectores por lo que aquí va:
- Realmente no desea tener FragmentManager y FragmentTransactions ocurriendo dentro de fragmentos para no tener Casts ni potenciales referencias dañinas a su Actividad (s)
Así que lo que hago y funciona muy bien se establece una interfaz para el fragmento y dar un método, diga needsHide ():
public class MyFrag extends Fragment { public interface MyFragInterface { public void needsHide(); }
Luego implementarlo en su Actividad:
public class MainActivity extends FragmentActivity implements MyFrag.MyFragInterface { public void needsHide() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //find the fragment by View or Tag MyFrag myFrag = (MyFrag)fragmentManager.findFragmentByTag(SOME_TAG); fragmentTransaction.hide(myFrag); fragmentTransaction.commit(); //do more if you must }}
La única parte que requiere pensar es cuándo llamar a needsHide (), esto se puede hacer en el fragmento de onViewCreated, ya que está seguro de que no es demasiado pronto para su MainActivity para cometer transacciones. Si lo coloca onCreate () puede que no funcione dependiendo de lo que haga con fragmentos oter:
@Override public void onViewCreated(View view, Bundle savedInstanceState) { // Making sure Main activity implemented interface try { if (USE_A_CONDITION) { ((MyFragInterface)this.getActivity()).needsHide(); } } catch (ClassCastException e) { throw new ClassCastException("Calling activity must implement MyFragInterface"); } super.onViewCreated(view, savedInstanceState); }
Simplemente, cree un método público en su actividad de "padre". Que esconde el fragmento.
Luego, desde dentro del fragmento en su evento click, obtenga el comando "parent | ' Actividad, ejecutarlo y luego llamar al método que creó.
((ParentActitity)getActivity()).hideFragment();
Usted podría intentar conseguir framelayout o fragmento por id y cambiar su visibilidad
View frag = findViewById(R.id.my_fragment); frag.setVisibility(View.VISIBLE);
Necesita utilizar una interfaz para comunicarse con su actividad principal.
Echa un vistazo al tutorial de Vogella, "3.4 Comunicación de la aplicación con Fragmentos". Aquí está el enlace
Method hide()
: Oculta un fragmento existente. Esto sólo es relevante para los fragmentos cuyas vistas se han agregado a un contenedor, ya que esto hará que la vista se oculte.
tu codigo :
@Override public void onClick(View v) { if(!menuVisible) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); fm.beginTransaction(); Fragment fragOne = new SubFragment(); ft.show(fragOne); } else { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); fm.beginTransaction(); // it's wrong , you just hide the fragment that not added to FragmentTransaction Fragment fragOne = new SubFragment(); ft.hide(fragOne); } }
Debajo de código trabajado para mí ..
View frag = findViewById(R.id.fragment); frag.setVisibility(View.GONE);//Or View.INVISBLE
- Dibujar texto en la parte superior de mapa de bits no
- ¿Cómo crear scripts de Renderscript en Android Studio y hacerlos funcionar?