Introducción
Los fragmentos son componentes modulares y reutilizables que representan una porción de la interfaz de usuario en una actividad. Permiten crear interfaces de usuario más flexibles y dinámicas, especialmente en aplicaciones que deben adaptarse a diferentes tamaños de pantalla, como teléfonos y tabletas.
Conceptos Clave
- Fragmento: Una porción de la interfaz de usuario que puede ser reutilizada en diferentes actividades.
- FragmentManager: Clase que maneja las transacciones de fragmentos dentro de una actividad.
- FragmentTransaction: Clase que permite realizar operaciones como agregar, reemplazar o eliminar fragmentos.
Creación de un Fragmento
Paso 1: Crear una Clase de Fragmento
Primero, crea una nueva clase que extienda Fragment. Aquí tienes un ejemplo básico:
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_example, container, false);
}
}Paso 2: Crear un Layout para el Fragmento
Crea un archivo XML en la carpeta res/layout para definir la interfaz de usuario del fragmento:
<!-- res/layout/fragment_example.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Fragment!" />
</LinearLayout>Paso 3: Agregar el Fragmento a una Actividad
Para agregar el fragmento a una actividad, usa el FragmentManager y FragmentTransaction:
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check if the fragment container is available
if (findViewById(R.id.fragment_container) != null) {
// Create a new Fragment to be placed in the activity layout
ExampleFragment firstFragment = new ExampleFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}Asegúrate de tener un contenedor en el layout de la actividad donde se colocará el fragmento:
<!-- res/layout/activity_main.xml -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />Comunicación entre Fragmentos
Para que los fragmentos se comuniquen entre sí, generalmente se utiliza la actividad que los contiene como intermediaria. Aquí hay un ejemplo básico de cómo hacerlo:
Paso 1: Definir una Interfaz en el Fragmento
public class ExampleFragment extends Fragment {
// Define an interface for communication
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String data);
}
private OnFragmentInteractionListener mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
// Call this method to send data to the activity
public void sendDataToActivity(String data) {
if (mListener != null) {
mListener.onFragmentInteraction(data);
}
}
}Paso 2: Implementar la Interfaz en la Actividad
public class MainActivity extends AppCompatActivity implements ExampleFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add the fragment to the activity
if (findViewById(R.id.fragment_container) != null) {
ExampleFragment firstFragment = new ExampleFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
@Override
public void onFragmentInteraction(String data) {
// Handle the data received from the fragment
Log.d("MainActivity", "Data received from fragment: " + data);
}
}Ejercicio Práctico
Ejercicio 1: Crear y Agregar un Fragmento
- Crea un nuevo fragmento llamado
SecondFragment. - Define un layout XML para
SecondFragmentque contenga unButton. - Modifica
MainActivitypara agregarSecondFragmental hacer clic en un botón enExampleFragment.
Solución
Paso 1: Crear SecondFragment
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
}Paso 2: Crear el Layout para SecondFragment
<!-- res/layout/fragment_second.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>Paso 3: Modificar MainActivity
public class MainActivity extends AppCompatActivity implements ExampleFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) != null) {
ExampleFragment firstFragment = new ExampleFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
@Override
public void onFragmentInteraction(String data) {
// Replace ExampleFragment with SecondFragment
SecondFragment secondFragment = new SecondFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, secondFragment)
.addToBackStack(null)
.commit();
}
}Paso 4: Modificar ExampleFragment para Enviar Datos
public class ExampleFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_example, container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onFragmentInteraction("Button Clicked");
}
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
}Conclusión
En esta sección, hemos aprendido cómo trabajar con fragmentos en Android. Hemos cubierto la creación de fragmentos, cómo agregarlos a una actividad y cómo permitir la comunicación entre fragmentos a través de la actividad. Los fragmentos son una herramienta poderosa para crear interfaces de usuario modulares y flexibles, y son esenciales para el desarrollo de aplicaciones Android modernas.
En el próximo módulo, exploraremos cómo manejar la entrada del usuario en nuestras aplicaciones Android.
Curso de Android Studio
Módulo 1: Introducción a Android Studio
- Introducción a Android Studio
- Configuración de Android Studio
- Entendiendo la interfaz de Android Studio
- Creando tu primer proyecto Android
Módulo 2: Desarrollo básico de Android
- Entendiendo la estructura del proyecto Android
- Introducción a los diseños XML
- Componentes básicos de la interfaz de usuario
- Introducción a las actividades
- Ejecutando tu aplicación en un emulador
Módulo 3: Desarrollo intermedio de Android
- Introducción a los Intents
- Trabajando con Fragmentos
- Manejo de la entrada del usuario
- Usando RecyclerView
- Redes en Android
Módulo 4: Desarrollo avanzado de Android
- Persistencia de datos con SQLite
- Usando Room para la gestión de bases de datos
- Componentes avanzados de la interfaz de usuario
- Vistas personalizadas y Canvas
- Trabajando con tareas en segundo plano
Módulo 5: Desarrollo profesional de Android
- Implementando la arquitectura MVVM
- Inyección de dependencias con Dagger
- Pruebas unitarias y pruebas de interfaz de usuario
- Publicando tu aplicación en Google Play
- Optimización del rendimiento
