Buscar..


Observaciones

Los fragmentos son componentes muy importantes de la interfaz de usuario en las aplicaciones de Android. Fueron introducidos por primera vez en la API de Android 3.0 (Honeycomb).


Entendiendo el paradigma de diseño de fragmentos.

Se introdujeron fragmentos para soportar principalmente la IU modular y flexible en dispositivos de pantalla grande, como tabletas.

Los fragmentos son gestionados por una actividad. Normalmente cada fragmento representa una porción de una pantalla. Puede haber más de un fragmento en una actividad. Los fragmentos también pueden ser llamados sub-actividades . Cuando agrega un fragmento como parte de su diseño de actividad, vive en un grupo de vistas dentro de la jerarquía de vistas de la actividad y el fragmento define su propio diseño de vista.


CICLO VITAL

Al igual que las actividades, los fragmentos también tienen un ciclo de vida. Un fragmento es notificado para los siguientes eventos.

  1. Apegarse a la actividad - onAttach (Actividad)
  2. Crear fragmento - onCreate (Bundle)
  3. Crear vista - onCreateView (LayoutInflater, ViewGroup, Bundle)
  4. Creación de actividad - onActivityCreated (Bundle)
  5. Estado de vista restaurado - onViewStateRestored (paquete)
  6. Hecho visible para el usuario - onStart ()
  7. inicio de la interacción del usuario - onResume ()
  8. pausa de la interacción del usuario - onPause ()
  9. Hecho invisible para el usuario - onStop ()
  10. En destrucción de vista - onDestroyView ()
  11. Destruir fragmento - onDestroy ()
  12. Desprenderse de una actividad - onDetach ()

Como programador, debe anular varios métodos de devolución de llamada del ciclo de vida, normalmente implementamos los métodos onCreate (), onCreateView () y onPause ().


Subclases de Fragmento

  1. DialogFragment - Para mostrar el diálogo flotante
  2. ListFragment - Para mostrar la lista de elementos
  3. PreferenceFragment - Útil para crear la actividad de configuración

Referencias

  1. https://developer.android.com/guide/components/fragments.html
  2. https://developer.android.com/reference/android/app/Fragment.html

Agregando Fragmentos

Agregar un fragmento estáticamente

Archivo: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
  
    <fragment  
        android:id="@+id/fragment2"  
        android:name="com.example.fragmentexample.Fragment2"  
        android:layout_width="0px"  
        android:layout_height="match_parent"   
        android:layout_weight="1"  
        />  
  
    <fragment  
        android:id="@+id/fragment1"  
        android:name="com.example.fragmentexample.Fragment1"  
        android:layout_width="0px"  
        android:layout_height="match_parent"  
        android:layout_weight="1"  
         />  
  
</LinearLayout>  

Archivo: fragment1.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:background="#00ff00"  
     >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="fragment frist"  
        android:textAppearance="?android:attr/textAppearanceLarge" />  
  
</LinearLayout>  

Archivo: fragment2.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:background="#0000ff"  
     >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Second Fragment"  
        android:textAppearance="?android:attr/textAppearanceLarge" />  
  
</LinearLayout>

Archivo: MainActivity.java

package com.example.fragmentexample;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
    }  
}  

Archivo: Fragment1.java

package com.example.fragmentexample;  
  
import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
  
public class Fragment1 extends Fragment {  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        return inflater.inflate(R.layout.fragment1,container, false);  
    }  
  
}  

Archivo: Fragment2.java

package com.example.fragmentexample;  
  
import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
  
public class Fragment2 extends Fragment {  
      
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        return inflater.inflate(R.layout.fragment2,container, false);  
    }  
  
}  

Añadiendo un fragmento dinámicamente

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
  
    <FrameLayout  
        android:id="@+id/container1"   
        android:layout_width="0px"  
        android:layout_height="match_parent"   
        android:layout_weight="1"  
        />  
  
    <FrameLayout  
        android:id="@+id/container2"   
        android:layout_width="0px"  
        android:layout_height="match_parent"  
        android:layout_weight="1"  
         />  
  
</LinearLayout>

FrameLayout está actuando como contenedor de fragmentos.

Clase de actividad principal

Archivo: MainActivity.java

package com.example.fragmentexample;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        loadFragment(this, R.id.container1,new Fragment1(),"fragment1");
        loadFragment(this, R.id.container2,new Fragment2(),"fragment2");    
    }  

    public static void loadFragment(Activity activity, int containerId, Fragment fragment, String tag)
    {
        activity.getSupportFragmentManager().beginTransaction().
            replace(containerId, fragment,tag).commitAllowingStateLoss();
    }
}  


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow