Lengüetas de la barra de la acción de Androide – problemas internos del trasaction del fragmento
He configurado correctamente pestañas en la barra de acciones con el siguiente ejemplo de Google ellos mismos en http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html as A bases Mi código parece así:
public class Main extends SherlockFragmentActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab1 = getSupportActionBar().newTab(); tab1.setIcon(R.drawable.ic_tab_example_selected); tab1.setTabListener(new TabListener<Tab1>(this, "A", Tab1.class)); getSupportActionBar().addTab(tab1); ActionBar.Tab tab2 = getSupportActionBar().newTab(); tab2.setIcon(R.drawable.ic_tab_example_selected); tab2.setTabListener(new TabListener<Tab2>(this, "B", Tab2.class)); getSupportActionBar().addTab(tab2); ActionBar.Tab tab3 = getSupportActionBar().newTab(); tab3.setIcon(R.drawable.ic_tab_example_selected); tab3.setTabListener(new TabListener<Tab3>(this, "C", Tab3.class)); getSupportActionBar().addTab(tab3); ActionBar.Tab tab4 = getSupportActionBar().newTab(); tab4.setIcon(R.drawable.ic_tab_example_selected); tab4.setTabListener(new TabListener<Tab4>(this, "D", Tab4.class)); getSupportActionBar().addTab(tab4); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } public class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final SherlockFragmentActivity mActivity; private final String mTag; private final Class<T> mClass; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } /* The following are each of the ActionBar.TabListener callbacks */ public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); } } public void onTabReselected(Tab tab, FragmentTransaction ft) { // User selected the already selected tab. Usually do nothing. } } }
Con esto tengo varias fichas que cambian entre los diferentes fragmentos en cada ficha. Sin embargo, mi problema comienza cuando en una pestaña y el cambio de fragmentos de dentro de una pestaña. Este es el problema:
- Manejo del título de ActionBar con la pila trasera del fragmento?
- Convertir la actividad en fragmento
- Puedo usar el paginador de vista con vistas (no con fragmentos)
- EventBus: la actividad no recibe un evento cuando la aplicación está en segundo plano
- ¿Es esta la manera correcta de limpiar la pila trasera Fragmento al dejar una pila anidadas?
Cuando estoy en la lengüeta 1 , intercambio el fragmento inicial cargado en la lengüeta con un nuevo fragmento. Luego voy a Tab 2 que muestra su fragmento inicial. Sin embargo, la vista del fragmento intercambiado en Tab 1 sigue mostrando detrás del fragmento Tab 2 :
Este es el código que estoy usando actualmente para cambiar el fragmento desde dentro de la pestaña 1 :
// Create new fragment and transaction FragmentTransaction transaction = ctx.getFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(container, fragment, tag); if(addToBackStack) transaction.addToBackStack(tag); // Commit the transaction transaction.commit();
Todo esto se está logrando a través de ActionBar Sherlock y la biblioteca de soporte de Google v4. Muchas gracias por cualquier ayuda por adelantado.
- ¿Cuando usas fragmentos de Android?
- Fragmentos parece ser excesivo? ¿No es posible una arquitectura MVC?
- Obtener todos los fragmentos de backstack en orden
- Establecer el título de la barra de herramientas
- Se hace clic en un diseño invisible detrás del fragmento:
- ¿Cuál es la "mejor práctica" para cambiar de "Actividades" a "Fragmentos" para aplicaciones de Android?
- Fragmento está en backstack
- ¿Por qué se arroja NPE al finalizar Actividad?
Ok, por lo que esta respuesta supone que desea borrar cada pestaña de nuevo historial cada vez que cambie las pestañas. Lo que quiero decir es que Tab 1 comienza en el fragmento 1, entonces usted hace clic y cambia a frag 2. Si selecciona Tab 2, va a deshacer el historial de Tab 1 y la próxima vez que haga clic en Tab 1 volverá a Frag 1.
Con eso dicho aquí está la solución: Reemplace su onTabUnselected con el siguiente
public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { //this segment removes the back history of everything in the tab you are leaving so when you click on the tab again you go back to a fresh start FragmentManager man = mActivity.getFragmentManager(); if(man.getBackStackEntryCount()>0) //this check is required to prevent null point exceptions when clicking off of a tab with no history man.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE); //this pops the stack back to index 0 so you can then detach and then later attach your initial fragment //also it should be noted that if you do popbackstackimmediate here instead of just popbackstack you will see a flash as the gui changes back to the first fragment when the code executes //end ft.detach(mFragment); } }