TabHost es un contenedor que contiene un conjunto de pestañas. Cada pestaña consta de la actividad o de los fragmentos . TabHost consta de dos hijos de los cuales uno es FrameLayout (que se usa para mostrar los contenidos de la actividad) y otro es TabWidget. (Se usa para elegir la pestaña que el usuario quiere abrir). Principalmente Tabhost se usa en el proyecto con la ayuda de LinearLayout .
Métodos importantes de TabHost
- addTab(TabSpec tabSpec): este método se usa para agregar la nueva pestaña a un widget de pestaña. Cada vez que se especifica una nueva pestaña usando la clase TabSpec, es necesario agregar esa pestaña en nuestro TabHost.
// iniciar TabHost
TabHost tabhost = (TabHost) findViewById(R.id.tabhost);
// configurando el tabhost
tabhost.setup();
// establecer el nombre de la nueva pestaña
TabHost.TabSpec spec = tabhost.newTabSpec(“Tab One”);
especificación.setContent(R.id.tab1);
spec.setIndicator(“Tab One”);
// agregar la pestaña a tabhost
tabhost.addTab(especificación);
- clearAllTabs(): este método se utiliza para borrar todas las pestañas dentro del host de pestañas. Después de agregar la pestaña como se muestra arriba, si alguien quiere borrar la pestaña de TabHost, escriba el siguiente código.
tabHost.clearAllTabs(); // este método se usa para borrar todas las pestañas de tabhost
- setOnTabChangedListener(OnTabChangeListener): este método se utiliza para registrar una devolución de llamada que debe invocarse cuando cambia el estado seleccionado de cualquiera de los elementos de esta lista. Este método se usa cuando se necesita invocar la devolución de llamada y registrarla cuando cambia el estado de cualquier elemento seleccionado en la lista.
- setCurrentTab (índice int): de forma predeterminada, los hosts de pestañas establecen la primera posición de la pestaña como la posición predeterminada que aparecerá cuando se inicie la aplicación, pero podemos cambiar explícitamente la posición predeterminada de la pestaña usando estos métodos. (La posición comienza desde 0)
tabHost.setCurrentTab(1); // establecerá la segunda pestaña como pestaña seleccionada por defecto
Ejemplo
Tratemos de entender TabHost en detalle haciendo un pequeño proyecto.
Implementación
Paso 1: Crear un nuevo proyecto
Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Tenga en cuenta que seleccione Java como lenguaje de programación.
Paso 2: trabajar con el archivo activity_main.xml
Ahora vaya al archivo activity_main.xml que representa la interfaz de usuario de la aplicación. A continuación se muestra el código para el archivo activity_main.xml .
XML
<?xml version="1.0" encoding="utf-8"?> <!--Linear layout as the root layout--> <LinearLayout 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" tools:context=".MainActivity"> <TabHost android:id="@+id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--Tab widget to select the tab--> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!--FrameLayout which contains the data of the activity--> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <!--for tab 1--> <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFC0CB" android:orientation="vertical"> <!--Text View for applying the text to the tab--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="270dp" android:text="This is Tab 1" android:textColor="#000" android:textSize="32sp" /> </LinearLayout> <!--for tab 2--> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#90ee90" android:orientation="vertical"> <!--Text View for applying the text to the tab--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="270dp" android:text="This is Tab 2" android:textColor="#000" android:textSize="32sp" /> </LinearLayout> <!--for tab 3--> <LinearLayout android:id="@+id/tab3" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#add8e6" android:orientation="vertical"> <!--Text View for applying the text to the tab--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="270dp" android:text="This is Tab 3" android:textColor="#000" android:textSize="32sp" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> </LinearLayout>
Paso 3: trabajar con el archivo MainActivity.kt
Vaya al archivo MainActivity.java y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.java . Se agregan comentarios dentro del código para comprender el código con más detalle.
Java
import android.os.Bundle; import android.widget.TabHost; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initiating the tabhost TabHost tabhost = (TabHost) findViewById(R.id.tabhost); // setting up the tab host tabhost.setup(); // Code for adding Tab 1 to the tabhost TabHost.TabSpec spec = tabhost.newTabSpec("Tab One"); spec.setContent(R.id.tab1); // setting the name of the tab 1 as "Tab One" spec.setIndicator("Tab One"); // adding the tab to tabhost tabhost.addTab(spec); // Code for adding Tab 2 to the tabhost spec = tabhost.newTabSpec("Tab Two"); spec.setContent(R.id.tab2); // setting the name of the tab 1 as "Tab Two" spec.setIndicator("Tab Two"); tabhost.addTab(spec); // Code for adding Tab 3 to the tabhost spec = tabhost.newTabSpec("Tab Three"); spec.setContent(R.id.tab3); spec.setIndicator("Tab Three"); tabhost.addTab(spec); } }
Producción:
Publicación traducida automáticamente
Artículo escrito por lavishgarg26 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA