Android TabWidget detectar clic en la pestaña actual
Estoy tratando de encontrar la manera de poder disparar un evento onclick en una pestaña cuando esta pestaña es la pestaña actual.
He intentado de esta manera (entre varios otros) sin éxito tú.
- Deshacerse de la línea bajo TabWidget
- Cómo hacer oval shape tabhost en android
- Cómo establecer la pestaña seleccionada debe estar en el centro
- Tabwidget se superpone con el contenido de mi actividad
- ¿Es posible usar el estilo ActionBarSherlock en TabWidget nativo?
public void onTabChanged(String tabId) { Log.d(this.getClass().getName(), ">>>>>>>>>>>>>>>>>>>>>>>> tabId: " + tabId); int tabs = getTabWidget().getChildCount(); Log.d(this.getClass().getName(), "tabs: " + tabs); for(int i=0; i<tabs; i++){ View tab = getTabWidget().getChildAt(i); if(i==tabHost.getCurrentTab()){ Log.d(this.getClass().getName(), "tab: " + i); tab.setOnClickListener(this); }else{ tab.setOnClickListener(null); tab.getOnFocusChangeListener(); } } }
El punto es que he puesto el onClickListener
a null
por lo que, la próxima vez que haga clic en una pestaña nada sucede, pero me gustaría tener el comportamiento de la pestaña normal .
¿Hay alguna idea ahí afuera?
- TabWidget - ¿Cómo establecer la posición del texto del indicador?
- Backbutton y pestañas de Android ActionBar
- Cómo aumentar la altura de la pestaña seleccionada en el widget de pestaña?
- Android 2.1 NullPointerException con TabWidgets
- Cómo cambiar el color del texto del indicador de tabs en android?
- Android TabWidget en tema de luz
- Cambiar color de texto y selector en TabWidget
- ¿Por qué obtengo una excepción de puntero nulo de TabWidget?
Después de muchas soluciones grough para el oyente de la lengüeta, he encontrado la solución muy simple …
getTabHost().setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { int i = getTabHost().getCurrentTab(); Log.i("@@@@@@@@ ANN CLICK TAB NUMBER", "------" + i); if (i == 0) { Log.i("@@@@@@@@@@ Inside onClick tab 0", "onClick tab"); } else if (i ==1) { Log.i("@@@@@@@@@@ Inside onClick tab 1", "onClick tab"); } } });
Después de pensar mucho en esto, la solución terminó siendo más fácil de lo que pensaba. Lo que hice fue crear una nueva clase de niño que extiende TabHost y anular el método setCurrentTab así:
package com.mycompany.Views; import android.content.Context; import android.util.AttributeSet; import android.widget.TabHost; import android.widget.Toast; public class ReclickableTabHost extends TabHost { public ReclickableTabHost(Context context) { super(context); } public ReclickableTabHost(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setCurrentTab(int index) { if (index == getCurrentTab()) { // FIRE OFF NEW LISTENER } else { super.setCurrentTab(index); } } }
Para usar su nueva clase en lugar de TabHost típico simplemente edite su archivo xml de diseño con:
<FrameLayout android:layout_height="match_parent" android:layout_width="0dip" android:layout_weight=".8"> <com.myCompany.Views.ReclickableTabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="gone"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/tab_unselected_holo"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> </FrameLayout> </LinearLayout> </com.myCompany.Views.ReclickableTabHost>
Espero que esto ayude…
Creo que he encontrado una solución, aquí sigue un código de ejemplo:
intent = new Intent(this, HomeGroup.class); View tab1 = _inflater.inflate(R.layout.custom_tab_1,null); homeTab.setTag("Tab1"); spec = tabHost.newTabSpec("Tab1").setIndicator(tab1).setContent(intent); tabHost.addTab(spec); View tab2 = _inflater.inflate(R.layout.custom_tab_2,null); homeTab.setTag("Tab2"); spec = tabHost.newTabSpec("Tab2").setIndicator(tab2).setContent(intent); tabHost.addTab(spec); View tab3 = _inflater.inflate(R.layout.custom_tab_3,null); homeTab.setTag("Tab3"); spec = tabHost.newTabSpec("Tab3").setIndicator(tab3).setContent(intent); tabHost.addTab(spec); tabHost.setOnTabChangedListener(this); //click on seleccted tab int numberOfTabs = tabHost.getTabWidget().getChildCount(); for(int t=0; t<numberOfTabs; t++){ tabHost.getTabWidget().getChildAt(t).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_UP){ String currentSelectedTag = MainTab.this.getTabHost().getCurrentTabTag(); String currentTag = (String)v.getTag(); Log.d(this.getClass().getSimpleName(), "currentSelectedTag: " + currentSelectedTag + " currentTag: " + currentTag); if(currentSelectedTag.equalsIgnoreCase(currentTag)){ MainTab.this.getTabHost().setCurrentTabByTag(currentTag); String newSelectedTabTag = MainTab.this.getTabHost().getCurrentTabTag(); if(newSelectedTabTag.toLowerCase().indexOf("tab1")!=-1){ //do smthg }else if(newSelectedTabTag.toLowerCase().indexOf("tab1")!=-1){ //do smthg }else if(newSelectedTabTag.toLowerCase().indexOf("tab3")!=-1){ //do smthg } return true; } } return false; } }); }
Probablemente es posible mejorarlo, pero esto hace el trabajo para mí!
Ugly fijar: EN el onClickListener puesto: tabHost.SetCurrentTab(OtherTab); tabHost.SetCurrentTab(CurrentTab);
tabHost.SetCurrentTab(OtherTab); tabHost.SetCurrentTab(CurrentTab);
Donde para el índice de la otra etiqueta utilizo mi visión más simple debajo de las lengüetas.
PS Los clientes siempre quieren que sus aplicaciones sean diferentes 🙂
Este es el código que uso (sólo tengo 2 pestañas Tab1 y Tab2):
getTabWidget().getChildAt(1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d(TAG,"1"+getTabHost().getCurrentTabTag()); if (getTabHost().getCurrentTabTag().equals("Tab2")) { Log.d(TAG,"2"); tabHost.setCurrentTab(0); tabHost.setCurrentTab(1); } else { tabHost.setCurrentTab(1); } } });
El problema aquí es que setOnTabChangedListener
no se dispara al hacer clic en la ficha seleccionada, y si establece un OnClickListener
en la ficha, pierde el comportamiento normal de la pestaña.
Así que una solución fácil es poner OnClickListener
en la pestaña, y dentro de ella, establecer programatically que esta es la pestaña actual.
Con TabHost
:
getTabWidget().getChildAt(0).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // custom code tabHost.setCurrentTab(0); } });
Con TabLayout
tabLayout.getTabAt(0)setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // custom code TabLayout.Tab tab = tabLayout.getTabAt(0); tab.select(); } } });
Si quieres probar android.support.design.widget.TabLayout , puedes conseguirlo así:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(Tab tab) { } @Override public void onTabUnselected(Tab tab) { } @Override public void onTabReselected(Tab tab) { } });
mTabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { int i = mTabHost.getCurrentTab(); mTabHost.getTabWidget().getChildAt(i) .setBackgroundColor(Color.parseColor("#014a68")); //int m = mTabHost.getChildCount(); for (int j = 0; j <=3; j++) { if (j != i) mTabHost.getTabWidget() .getChildAt(j) .setBackgroundColor(Color.parseColor("#000000")); } } });
Si tiene un diseño de pestaña personalizado, puede que deba añadirlo en su vista personalizada, resolvió mi problema:
android:duplicateParentState="true"
- Clase para simplificar la creación de subprocesos de fondo y la sincronización de subprocesos de interfaz de usuario
- Cómo hacer referencia a la actividad actual o principal de otra clase