Cómo desplazar tablayout programatically – Android

He creado 30 pestañas desplazables usando tablayout.

Así que las primeras tres pestañas son visibles en la pantalla y el resto de ellas son invisibles, que pueden desplazarse con un gesto de desplazamiento.

El problema es cuando estoy seleccionando la última pestaña programáticamente pero no es visible (el diseño de la pestaña no se desplaza hasta la última pestaña).

¿Cómo puedo hacer tablayout para desplazarse a la última pestaña?

Gracias por adelantado.

Encontré la solución.

En primer lugar, había encontrado el ancho de tablayout y desplazar su posición x a ancho y que se llama el método select () de la última pestaña.

Y funciona bien.

A continuación se muestra el código.

mTabLayout.setScrollX(mTabLayout.getWidth()); mTabLayout.getTabAt(lastTabIndex).select(); 

Actualizado :

Si arriba no está trabajando usted puede utilizar el código abajo también, también está trabajando muy bien.

 new Handler().postDelayed( new Runnable() { @Override public void run() { mTabLayout.getTabAt(TAB_NUMBER).select(); } }, 100); 

He encontrado esta solución para mí:

  TabLayout tabLayout = activity.getTabLayout(); tabLayout.setSmoothScrollingEnabled(true); tabLayout.setScrollPosition(targetChannelPosition, 0f, true); 

También, si recibe este error: "Sólo el subproceso original que creó una jerarquía de vista puede tocar sus vistas.", Puede utilizar este código, para ejecutar en subproceso Ui:

  // find a way to get the activity containing the tab layout TabLayout tabLayout = activity.getTabLayout(); activity.runOnUiThread(new Runnable() { @Override public void run() { TabLayout.Tab tab = tabLayout.getTabAt(targetChannelPosition); tab.select(); } }); 

La respuesta anterior no funcionaría porque primero Como agirardello mencionó no debes usar mTabLayout.getWidth() ya que no devuelve lo que necesitamos (que es la posición del niño al que quieres desplazarte) y la solución actualizada no ' T siempre funcionan debido a un error en TabLayout (informado aquí ) pero un trabajo alrededor es simple.

Las pestañas de la tabLayout no son hijos directos de TabLayout por lo que tenemos que ir un nivel más profundo con

 ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(YOUR_DESIRED_TAB_INDEX).getRight() 

El único hijo de tabLayout es un TabLayout.SlidingTabStrip que también es un ViewGroup y getRight() nos dará la posición más correcta de nuestra vista de pestaña deseada. Así, el desplazamiento a esa posición nos dará lo que deseamos. Aquí está un código completo:

 int right = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(4).getRight(); mTabLayout.scrollTo(right,0); mTabLayout.getTabAt(4).select(); 

NOTA: Asegúrese de que está llamando a estos métodos después de que el diseño se haya ahogado (como onResume y no onCreate)

Espero que esto ayude.

Escriba este método en su tablayout personalizado (su propio diseño que extiende tablayout). Por lo tanto, en el futuro puede utilizar este método siempre que necesite instad de duplicación de código

 public void selectTabAt(int tabIndex) { if (tabIndex >= 0 && tabIndex < getTabCount() && getSelectedTabPosition() != tabIndex) { final Tab currentTab = getTabAt(tabIndex); if (currentTab != null) { this.post(new Runnable() { @Override public void run() { currentTab.select(); } }); } } } 

Si no desea utilizar CustomLayout. Solo puedes hacer esto

 final Tab currentTab = mTabLayout.getTabAt(tabIndex); if(currentTab != null){ mTabLayout.post(new Runnable() { @Override public void run() { currentTab.select(); } }); } 

Para seleccionar la última pestaña, utilice tabLayout.getTabAt (X) .select (); Donde X es el último índice de pestañas

¿Está llamando a tab.select() antes de TabLayout y sus hijos han sido medidos y dibujados? Si es así, su TabLayout no se animará a la selección con tab.select() (o la sugerencia de Kayvan N de scrollTo() ). El uso de un controlador probablemente funcionará, pero no es una solución ideal.

Siempre que el diseño no se haya establecido aún, un ViewTreeObserver le permitirá moverse a la pestaña seleccionada después de que el proceso de diseño haya terminado.

 private void scrollToTabAfterLayout(final int tabIndex) { if (getView() != null) { final ViewTreeObserver observer = mTabLayout.getViewTreeObserver(); if (observer.isAlive()) { observer.dispatchOnGlobalLayout(); // In case a previous call is waiting when this call is made observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { observer.removeOnGlobalLayoutListener(this); } else { //noinspection deprecation observer.removeGlobalOnLayoutListener(this); } mTabLayout.getTabAt(tabIndex).select(); } }); } } } 

Por favor, comente si tiene alguna sugerencia.

viewpager.setItem(position) también debe establecer la posición de la pestaña

Esta solución funcionó para mí. Mi situación es un poco diferente; En mi caso, estoy usando el TabLayout con un ViewPager y agregando más vistas y llamando a notifyDataSetChange ().

La solución es establecer una devolución de llamada en el observador de TabLayout y desplazarse cuando los niños realmente se agregan a TabLayout. Aquí está mi ejemplo:

 /** Keep in mind this is how I set my TabLayout up... PagerAdapter pagerAdapter = new PagerAdapter(...); ViewPager pager = (ViewPager)findViewById(...); pager.setAdapter(pagerAdapter); TabLayout tabLayout = (TabLayout)findViewById(...); tabLayout.setupWithViewPager(pager); */ public void loadTabs(String[] topics) { animateTabsOpen(); // Irrelevant to solution // Removes fragments from ViewPager pagerAdapter.clear(); // Adds new fragments to ViewPager for (String t : topics) pagerAdapter.append(t, new TestFragment()); // Since we need observer callback to still animate tabs when we // scroll, it is essential to keep track of the state. Declare this // as a global variable scrollToFirst = true; // Alerts ViewPager data has been changed pagerAdapter.notifyOnDataSetChanged(); // Scroll to the beginning (or any position you need) in TabLayout // using its observer callbacks tabs.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { /** We use onGlobalLayout() callback because anytime a tab is added or removed the TabLayout triggers this; therefore, we use it to scroll to the desired position we want. In my case I wanted to scroll to the beginning position, but this can easily be modified to scroll to any position. */ if (scrollToFirst) { tabs.getTabAt(0).select(); tabs.scrollTo(0, 0); scrollToFirst = false; } } }); } 

Aquí está mi código para el PagerAdapter si usted lo necesita demasiado lol:

 public class PagerAdapter extends FragmentStatePagerAdapter { private List<Fragment> fragments; private List<String> titles; public PagerAdapter(FragmentManager fm) { super(fm); this.fragments = new ArrayList<>(); this.titles = new ArrayList<>(); } /** * Adds an adapter item (title and fragment) and * doesn't notify that data has changed. * * NOTE: Remember to call notifyDataSetChanged()! * @param title Fragment title * @param frag Fragment * @return This */ public PagerAdapter append(String title, Fragment frag) { this.titles.add(title); this.fragments.add(frag); return this; } /** * Clears all adapter items and doesn't notify that data * has changed. * * NOTE: Rememeber to call notifyDataSetChanged()! * @return This */ public PagerAdapter clear() { this.titles.clear(); this.fragments.clear(); return this; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } @Override public int getCount() { return fragments.size(); } @Override public int getItemPosition(Object object) { int position = fragments.indexOf(object); return (position >= 0) ? position : POSITION_NONE; } } 
 new Handler().postDelayed( new Runnable() { @Override public void run() { mTabLayout.getTabAt(TAB_NUMBER).select(); } }, 100); 

Me pregunto si esta es la respuesta será relevante ya que viene muy tarde. En realidad lo logré en C # utilizando Xamarin.

 tabs.GetChildAt(0).Selected = true; viewPager.SetCurrentItem(0, true); 

Si su TabLayout se utiliza conjuntamente con un ViewPager , que es común, simplemente agregue lo siguiente en el método onCreate() en su Actividad:

 tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout); 

Que algunas de sus pestañas no se muestran indica que el atributo tabMode está configurado como app:tabMode="scrollable" .

  • Cómo personalizar las pestañas de Android o cambio de fondo?
  • Cómo configurar las pestañas en la parte inferior de la pantalla en android?
  • Cómo implementar PageTransformer con pestañas deslizables
  • Align-Center SlidingTabLayout
  • Ocultar pestañas en el visor
  • Cómo Estilo ActionBar, ficha fondo en la pestaña seleccionada
  • Android, pestañas sin Barra de Acción
  • Tablayout sólo con iconos
  • Fragmento dentro de la pestaña en Android
  • Añadir pestaña dentro de Fragmento ¿En Android?
  • ¿Cómo iniciar una actividad con una pestaña específica?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.