{"id":23701183,"url":"https://github.com/gitfrandu4/android-navigation-fragments","last_synced_at":"2025-07-19T13:36:36.574Z","repository":{"id":211625154,"uuid":"549083930","full_name":"gitfrandu4/android-navigation-fragments","owner":"gitfrandu4","description":"Intro to Android. Fragments - Navigation II","archived":false,"fork":false,"pushed_at":"2022-10-10T17:57:55.000Z","size":1009,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-12-30T09:32:49.024Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gitfrandu4.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-10-10T16:42:21.000Z","updated_at":"2022-10-10T17:00:23.000Z","dependencies_parsed_at":"2023-12-09T19:52:43.916Z","dependency_job_id":null,"html_url":"https://github.com/gitfrandu4/android-navigation-fragments","commit_stats":null,"previous_names":["gitfrandu4/android-navigation-fragments"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gitfrandu4%2Fandroid-navigation-fragments","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gitfrandu4%2Fandroid-navigation-fragments/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gitfrandu4%2Fandroid-navigation-fragments/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gitfrandu4%2Fandroid-navigation-fragments/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gitfrandu4","download_url":"https://codeload.github.com/gitfrandu4/android-navigation-fragments/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239776654,"owners_count":19695148,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-30T09:32:32.738Z","updated_at":"2025-02-20T04:27:21.685Z","avatar_url":"https://github.com/gitfrandu4.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Navegación II\n\n## Fragments\n\nLos fragment forman parte del activity, se complementan. Lo normal es tener un Activity que va a \ncontener muchos Fragments\n\n### Qué son y sus ciclos de vida\n\nUn fragmento es un componente de Android que contiene parte del comportamiento y / o la interfaz de\nusuario de una actividad. Los fragmentos están vinculados a una sola actividad. En muchos sentidos,\ntienen una funcionalidad similar a la de las actividades.\n\n*Imagina por un momento que eres una actividad. Tienes mucho que hacer, por lo que puedes emplear a\nunos pocos minions para que te lleven la ropa y paguen impuestos a cambio de alojamiento y comida.\nEso es algo así como la relación entre actividades y fragmentos.*\n\nNo es un requisito utilizar fragments, porque tu mismo puedes lavar tu ropa y pagar tus impuestos,\npero si los usas bien pueden proporcionar:\n\n* **Modularidad**: dividir código de actividad complejo entre fragmentos para una mejor organización\n  y mantenimiento.\n\n* **Reusabilidad**: colocar el comportamiento o las partes de la IU en fragmentos que pueden\n  compartirse en múltiples actividades.\n\n* **Adaptabilidad**: representa secciones de una interfaz de usuario como diferentes fragmentos y\n  utiliza diferentes diseños según la orientación y el tamaño de la pantalla.\n\nTutorial para aprenderlo todo sobre los\nfragments: https://www.raywenderlich.com/169885/android-fragments-tutorial-introduction-2\n\n\u003cimg src=\"imgs/fragment-1.png\" alt=\"fragment 1\" style=\"max-width: 100%;max-height: 240px;\"\u003e\n\n**Vamos a crear dos Fragment**\n\nNos tiene que quedar así:\n\n```kotlin\nclass BlueFragment : Fragment() {\n    override fun onCreateView(\n        inflater: LayoutInflater, container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View? {\n        // Inflate the layout for this fragment\n        return inflater.inflate(R.layout.fragment_blue, container, false)\n    }\n}\n```\n\n\u003cimg src=\"imgs/fragment-2.png\" alt=\"fragment 2\" style=\"max-width: 100%;max-height: 240px;\"\u003e\n\n**¿Cómo crear un fragment?**\n\n\u003cimg src=\"imgs/fragment-3.png\" alt=\"fragment 3\" style=\"max-width: 100%;max-height: 240px;\"\u003e\n\n### Navegación con Fragments\n\n1. Necesitamos crear un FragmentContainerView en una Activity como \"contenedor\" donde meter nuestro\n   Fragment\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\" android:orientation=\"vertical\"\n    tools:context=\".Main2Activity\"\u003e\n\n    \u003candroidx.fragment.app.FragmentContainerView android:id=\"@+id/mainContainer\"\n        android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nEste código lo pegaríamos, en nuestro ejemplo, en el ActivityMain\n\n2. En el Activity, le decimos que en el **FragmentContainerView** tiene que estar nuestro Fragment\n\n```kotlin\nclass MainActivity : AppCompatActivity() {\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main2)\n\n        supportFragmentManager.beginTransaction().replace(R.id.mainContainer, BlueFragment())\n            .commit()\n    }\n}\n```\n\n### Volver atrás\n\nSi necesitamos volver atrás entre fragments, antes de lanzarlo hay que añadirlo a una “pila” que se\nllama “backStack”. De esa manera se guardará que en algún momento querremos volver atrás.\n\nEstos serian los pasos:\n\n1. Lanzar el primer fragment desde la activity, a este no queremos volver atrás, si no que será el\n   principal\n\n```kotlin\nclass MainActivity : AppCompatActivity() {\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main2)\n\n        supportFragmentManager\n            .beginTransaction()\n            .replace(R.id.mainContainer, BlueFragment())\n            .addToBackStack(\"BlueFragment\").commit() // \u003c======\n\n        // Ahora al ejecutar estariamos viendo un Activity que contiene un Fragment dentro\n    }\n}\n```\n\n\u003cimg src=\"imgs/volver-atras-1.png\" alt=\"volver atrás\" style=\"max-width: 100%;max-height: 240px;\"\u003e\n\n2. Desde el fragment “BlueFragment” llamaremos al “RedFragment” al pulsar un botón y le diremos que\n   nos guarde el fragment en la pila\n\n```kotlin\nclass BlueFragment : Fragment() {\n    override fun onCreateView(\n        inflater: LayoutInflater,\n        container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View? {\n\n        // Inflate the layout for this fragment\n        return inflater.inflate(R.layout.fragment_blue, container, false)\n    }\n\n    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n        super.onViewCreated(view, savedInstanceState)\n\n        btIrRojo.setOnClickListener {\n            activity!!.supportFragmentManager.beginTransaction()\n                .replace(R.id.mainContainer, RedFragment()).addToBackStack(\"RedFragment\").commit()\n        }\n    }\n}\n```\n\n\u003cimg src=\"imgs/volver-atras-1.png\" alt=\"volver atrás\" style=\"max-width: 100%;max-height: 240px;\"\u003e\n\n#### Pasar parámetros entre fragments\n\nDesde el fragment “BlueFragment” al instanciar “RedFragment” iniciaremos los arguments y le\npasaremos los datos que necesitemos para leer en el otro fragment\n\n```kotlin\nclass BlueFragment : Fragment() {\n    override fun onCreateView(\n        inflater: LayoutInflater, container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View? {\n        return inflater.inflate(R.layout.fragment_blue, container, false)\n    }\n    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n        super.onViewCreated(view, savedInstanceState)\n        btIrRojo.setOnClickListener {\n            activity?.let {\n                val fragment = RedFragment()\n                fragment.arguments = Bundle().apply {\n                    putString(\"nombre\", \"Charles\")\n                }\n                it.supportFragmentManager.beginTransaction().replace(R.id.container, fragment)\n                    .addToBackStack(\"\").commit()\n            }\n        }\n    }\n}\n```\n\nBundle es com un conjunto de elementos donde podemos meter atributos en el Fragment\n\n#### Leer parámetros entre fragments\n\nDesde el fragment “RedFragment” leeremos nuestro parametro usando el atributo arguments y gestString\ncon el nombre que le dimos a nuestro argumento.\n\n```kotlin\noverride fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n    super.onViewCreated(view, savedInstanceState)\n\n    val nombre = arguments?.getString(\"nombre\")\n    Log.i(\"RedFragment\", nombre)\n}\n```\n\n### Volver atrás por código\n\n3. Y ahora, volveremos atrás desde el \"RedFragment\" al \"BlueFragment\"\n\n```kotlin\nclass RedFragment : Fragment() {\n    override fun onCreateView(\n        inflater: LayoutInflater,\n        container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View? {\n        // Inflate the layout for this fragment\n        return inflater.inflate(R.layout.fragment_red, container, false)\n    }\n    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n        super.onViewCreated(view, savedInstanceState)\n        btnBack.setOnClickListener {\n            activity?.supportFragmentManager?.popBackStack()\n        }\n    }\n}\n```\n\nPara más información ver:\nhttps://developer.android.com/guide/components/fragments?hl=es_419","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgitfrandu4%2Fandroid-navigation-fragments","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgitfrandu4%2Fandroid-navigation-fragments","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgitfrandu4%2Fandroid-navigation-fragments/lists"}