Os fragmentos foram criados com o objetivo modularizar a parte gráfica do app. Cada uma dessas partes possui seu próprio layout, clico de vida e necessitam de uma atividade. Conforme consta na documentação oficial, Google Developers (2021), "Um fragmento representa uma parte reutilizável da IU do seu app. Um fragmento define e gerencia o próprio layout, tem o próprio ciclo de vida e pode processar os próprios eventos de entrada. Fragmentos não podem existir por conta própria" .
Referências do texto entre aspas:
-
GOOGLE DEVELOPERS. Fragmentos. Disponível em: https://developer.android.com/guide/fragments#videos. Acesso em: 04 de ago. 2024.
Os fragmentos também possuem um ciclo de vida, sendo que o método mais relevante é o onCreateView que será chamado para criar a interface gráfica personalizada no arquivo de layout especifico do fragmento. O método retorna uma View que representa a raiz do layout do fragmento. Para a activity o fragmento será visto como mais uma view inserida em seu layout.
Métodos do ciclo de vida:
-
onAttach(Context context): o fragmento é anexado ao contexto da activity;
-
onCreate(Bundle savedInstanceState): cria o fragmento, pode ser usado para passar informações vinculadas ao objeto Bundle;
-
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): retorna a View criada a partir do layout personalizado do fragmento;
-
onViewCreated(View view, Bundle savedInstanceState):invocado logo após a criação da View. Pode ser usado para adicionar eventos, ou outras configurações de interface gráfica;
-
onStart(): a mesma tarefa definida na activity, ou seja, está visível, mas não aceita solicitações do usuário;
-
onResume(): a mesma tarefa definida na activity, ou seja, visível e responde ao usuário;
-
onPause(): a mesma tarefa definida na activity, ou seja, é chamado quando o fragmento está parcialmente visível;
-
onStop(): a mesma tarefa definida na activity, ou seja, é chamado quando o fragmento não está mais visível;
-
onDestroyView(): método chamado quando a view do fragmento é destruída. Pode ser usado para liberar recursos associados à interface do usuário;
-
onDestroy(): chamado para encerrar o fragmento;
-
onDetach(): o fragmento é desassociado da activity.
-
Referência: GOOGLE DEVELOPERS. Ciclo de Vida dos Fragmentos. Disponível em:https://developer.android.com/guide/fragments/lifecycle?hl=pt-br. Acessado em: 26 ago. 2024.
Exemplos práticos (estático):
-
colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="red">#CE3D3D</color> <color name="green">#4CAF50</color> </resources>
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <fragment android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:name="com.example.fragment_01.Tela1" android:id="@+id/tela1"/> <fragment android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:name="com.example.fragment_01.Tela2" android:id="@+id/tela2"/> </LinearLayout>
-
MainActivity.java
import android.os.Bundle; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
-
tela1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@color/green" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextNome" android:hint="Digite seu nome"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/buttonNome" android:text="CLICK"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewNome"/> </LinearLayout>
-
Tela1.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class Tela1 extends Fragment { private EditText editText; private Button button; private TextView textView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tela1,container, false); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editText = view.findViewById(R.id.editTextNome); button = view.findViewById(R.id.buttonNome); textView = view.findViewById(R.id.textViewNome); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView.setText(editText.getText().toString()); } }); } }
-
tela2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@color/red" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextCurso" android:hint="Digite o curso"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/buttonCurso" android:text="CLICK"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewCurso"/> </LinearLayout>
-
Tela2.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class Tela2 extends Fragment { private EditText editText; private Button button; private TextView textView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tela2, container, false); return view; }//method @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editText = view.findViewById(R.id.editTextCurso); button = view.findViewById(R.id.buttonCurso); textView = view.findViewById(R.id.textViewCurso); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView.setText(editText.getText().toString()); } }); } }
Exemplos práticos (dinâmico):
-
colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="green">#4CAF50</color> <color name="orange">#FF9800</color> <color name="blue">#00BCD4</color> <color name="red">#E91E63</color> </resources>
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/orange" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_weight="1" android:text="Tela1" android:onClick="trocar" android:id="@+id/buttonTela1" android:layout_height="wrap_content"/> <Button android:layout_width="0dp" android:layout_weight="1" android:text="Tela2" android:onClick="trocar" android:id="@+id/buttonTela2" android:layout_height="wrap_content"/> </LinearLayout> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/red" android:id="@+id/telaPrincipal" /> </LinearLayout>
-
MainActivity.java
import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class MainActivity extends AppCompatActivity { private Button buttonTela1,buttonTela2; private FragmentManager fm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonTela1 = findViewById(R.id.buttonTela1); buttonTela2 = findViewById(R.id.buttonTela2); fm = getSupportFragmentManager(); // Carrega a tela 1 FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.telaPrincipal, new Tela1()); ft.commit(); } public void trocar(View view){ if(view.getId() == R.id.buttonTela1){ FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.telaPrincipal, new Tela1()); ft.commit(); //confirmar } if(view.getId() == R.id.buttonTela2){ FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.telaPrincipal, new Tela2()); ft.commit(); } }// }
-
tela1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@color/green" android:orientation="vertical" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextNome" android:hint="Digite seu nome"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/buttonNome" android:text="CLICK"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewNome" /> </LinearLayout>
-
Tela1.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class Tela1 extends Fragment { private EditText editText; private Button button; private TextView textView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tela1,container, false); return view; }//method @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editText = view.findViewById(R.id.editTextNome); button = view.findViewById(R.id.buttonNome); textView = view.findViewById(R.id.textViewNome); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView.setText(editText.getText().toString()); } }); } }
-
tela2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@color/blue" android:orientation="vertical" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextCurso" android:hint="Digite o curso"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/buttonCurso" android:text="CLICK"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewCurso" /> </LinearLayout>
-
Tela2.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class Tela2 extends Fragment { private EditText editText; private Button button; private TextView textView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tela2,container,false); return view; }//method @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editText = view.findViewById(R.id.editTextCurso); button = view.findViewById(R.id.buttonCurso); textView = view.findViewById(R.id.textViewCurso); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView.setText(editText.getText().toString()); } }); } }
Veja que na documentação oficial(https://developer.android.com/guide/fragments/create?hl=pt-br), que a tag para adicionar o fragmento foi atualizada para <androidx.fragment.app.FragmentContainerView>. A mesma tag pode ser usada tanto para adicionar o fragmento via XML como programaticamente. A diferença é que para adicionar via XML, deve ser usado o atributo name, passando o nome da classe java que estende a classe Fragment. Caso deseje adicionar de forma dinâmica use o atributo id.
Por exemplo: no arquivo activity_main.xml a nova tag adicionada ficaria assim:
<androidx.fragment.app.FragmentContainerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tela" />
Na classe MainActivity, coloque o gerenciamento de fragmento no método onCreate.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.tela, FragmentActivity.class,null)
.commit();
}
Exemplos práticos (FragContentView):
-
colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="green">#4CAF50</color> <color name="orange">#FF9800</color> <color name="blue">#00BCD4</color> <color name="red">#E91E63</color> </resources>
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <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" android:orientation="vertical" android:background="@color/orange" tools:context=".MainActivity"> <androidx.fragment.app.FragmentContainerView android:id="@+id/telaPrincipal" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/green" tools:layout="@layout/tela1" /> </LinearLayout>
-
tela1.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:gravity="center" android:padding="24dp" android:background="@android:color/holo_blue_light"> <TextView android:id="@+id/textViewMensagem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Olá, você está na Tela 1!" android:textSize="20sp" android:textColor="@android:color/white" /> <Button android:id="@+id/buttonMensagem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clique aqui" android:layout_marginTop="16dp" /> </LinearLayout>
-
Tela1.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class Tela1 extends Fragment { private TextView textView; private Button button; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.tela1, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); textView = view.findViewById(R.id.textViewMensagem); button = view.findViewById(R.id.buttonMensagem); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText("Você clicou no botão da Tela 1!"); } }); } }
-
MainActivity.java
import android.os.Bundle; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.telaPrincipal, new Tela1()); ft.commit(); } }
Exemplo mostrando a interação do clico de vida da Activity e dos Fragments:
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Trocar Fragmento" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
-
fragment_imagem.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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=".ImagemFragment"> <ImageView android:id="@+id/imagem" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/ic_launcher_foreground" tools:srcCompat="@tools:sample/avatars" /> </FrameLayout>
-
fragment_lista.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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=".ListaFragment"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </FrameLayout>
-
MainActivity.java
import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class MainActivity extends AppCompatActivity { private boolean controleFragment = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //permite que você exiba visualizações atrás da barra de status EdgeToEdge.enable(this); setContentView(R.layout.activity_main); //insets barra de status no topo da tela // ou a barra de navegação na parte inferior. //garantir que o conteúdo da tela // não fique oculto ou sobreposto por esses elementos do sistema. ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); Log.i("Activity","Criada"); if (savedInstanceState == null) { mostrar(new ImagemFragment()); } Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Alterna entre os fragmentos if (controleFragment) { mostrar(new ListaFragment()); } else { mostrar(new ImagemFragment()); } controleFragment = !controleFragment; } }); }// private void mostrar(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } @Override protected void onPause() { super.onPause(); Log.i("Activity","Pausada"); } @Override protected void onResume() { super.onResume(); Log.i("Activity","Pronta"); } @Override protected void onStart() { super.onStart(); Log.i("Activity","Inicializada"); } @Override protected void onStop() { super.onStop(); Log.i("Activity","Parada"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("Activity","Destruída"); } }//
-
ImagemFragment.java
import android.content.Context; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ImagemFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Log.e("Fragment","criando a view"); return inflater.inflate(R.layout.fragment_imagem, container, false); }// @Override public void onAttach(@NonNull Context context) { super.onAttach(context); Log.e("Fragment","anexado"); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("Fragment","criado"); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.e("Fragment","view já criada"); } @Override public void onStart() { super.onStart(); Log.e("Fragment","inicializado"); } @Override public void onResume() { super.onResume(); Log.e("Fragment","pronto"); } @Override public void onStop() { super.onStop(); Log.e("Fragment","parado"); } @Override public void onDestroy() { super.onDestroy(); Log.e("Fragment","destroi o fragmento"); } @Override public void onDetach() { super.onDetach(); Log.e("Fragment","desassocia o fragmento à actividade"); } @Override public void onDestroyView() { super.onDestroyView(); Log.e("Fragment","destroi a view do fragmento"); } @Override public void onPause() { super.onPause(); Log.e("Fragment","pausado"); } }//class
-
ListaFragment.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class ListaFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_lista, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ListView listView = view.findViewById(R.id.list_view); String[] items = {"Java", "Python", "Kotlin"}; ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter); } }
Exemplos práticos (Passando valor da activity para o fragmento):
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.fragment.app.FragmentContainerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
-
MainActivity.java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { Bundle bundle = new Bundle(); bundle.putInt("number", 10); getSupportFragmentManager().beginTransaction() .setReorderingAllowed(true) .add(R.id.fragment_container_view, ExampleFragment.class, bundle) .commit(); } } }
-
example_fragment.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:padding="16dp"> <TextView android:id="@+id/textViewHello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Texto padrão" android:textSize="20sp"/> </LinearLayout>
-
ExampleFragment.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.example_fragment, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { Integer msg = bundle.getInt("number"); TextView textViewHello = view.findViewById(R.id.textViewHello); textViewHello.setText(msg.toString()); } } }
Exemplos práticos (Comunicação entre Fragment e Activity):
-
fragment_mensagem.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="wrap_content" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/editTextMensagem" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Digite algo" /> <Button android:id="@+id/buttonEnviar" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Enviar" /> </LinearLayout>
-
FragmentMensagem.java
import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; public class FragmentMensagem extends Fragment { private EditText editText; private Button button; private EnviarMensagemListener listener; // Interface de comunicação com a Activity public interface EnviarMensagemListener { void onMensagemEnviada(String texto); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof EnviarMensagemListener) { listener = (EnviarMensagemListener) context; } } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mensagem, container, false); editText = view.findViewById(R.id.editTextMensagem); button = view.findViewById(R.id.buttonEnviar); button.setOnClickListener(v -> { String texto = editText.getText().toString(); if (listener != null) { listener.onMensagemEnviada(texto); } }); return view; } }
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/containerFragment" android:layout_width="match_parent" android:layout_height="match_parent" />
-
MainActivity.java
import android.os.Bundle; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements FragmentMensagem.EnviarMensagemListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.containerFragment, new FragmentMensagem()) .commit(); } } @Override public void onMensagemEnviada(String texto) { Toast.makeText(this, "Recebido do Fragmento: " + texto, Toast.LENGTH_SHORT).show(); } }
Exemplos práticos (maneiras de trocar os fragmentos):
-
colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="green">#8BC34A</color> <color name="blue">#00BCD4</color> </resources>
-
fragment_one.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/green"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Fragmento 1" android:gravity="center" android:textAppearance="@style/TextAppearance.AppCompat.Medium" /> </FrameLayout>
-
fragment_two.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/blue"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Fragmento 2" android:gravity="center" android:textAppearance="@style/TextAppearance.AppCompat.Medium" /> </FrameLayout>
-
FragmentOne.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class FragmentOne extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_one, container, false); } }
-
FragmentTwo.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class FragmentTwo extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_two, container, false); } }
-
ActivityMain.java
import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class MainActivity extends AppCompatActivity { FragmentManager fragmentManager; FragmentTransaction transaction; boolean adicionado = false; Fragment fragmentOne, fragmentTwo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); fragmentOne = new FragmentOne(); fragmentTwo = new FragmentTwo(); getSupportFragmentManager().beginTransaction() .add(R.id.container, fragmentOne) .commit(); findViewById(R.id.buttonTrocar).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.container, fragmentTwo); transaction.commit(); } }); findViewById(R.id.buttonRetornar). setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.container, fragmentTwo); transaction.addToBackStack(null); // permite voltar para a tela anterior transaction.commit(); } }); findViewById(R.id.buttonOcultar).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { transaction = fragmentManager.beginTransaction(); if (!adicionado) { // Adiciona o fragmento2 e esconde o fragmento1 //ambos ficam na memória transaction.hide(fragmentOne); transaction.add(R.id.container, fragmentTwo); adicionado = true; } else { // Alterna entre os dois if (fragmentTwo.isHidden()) { transaction.hide(fragmentOne); transaction.show(fragmentTwo); } else { transaction.hide(fragmentTwo); transaction.show(fragmentOne); } } transaction.commit(); } }); } }
Exemplos práticos (lista com 4 itens e cada item é mostrado usando fragmentos):
-
strings.xml
<resources> <string name="app_name">FragLista</string> <!-- Nomes das Estrelas --> <string name="estrela_1_nome">Estrela 1</string> <string name="estrela_2_nome">Estrela 2</string> <string name="estrela_3_nome">Estrela 3</string> <!-- Descrições das Estrelas --> <string name="estrela_1_descricao">Descrição detalhada da Estrela 1.</string> <string name="estrela_2_descricao">Descrição detalhada da Estrela 2.</string> <string name="estrela_3_descricao">Descrição detalhada da Estrela 3.</string> </resources>
-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
-
MainActivity.java
import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class MainActivity extends AppCompatActivity implements EstrelaAdapter.OnItemClickListener { private RecyclerView recyclerView; private EstrelaAdapter estrelaAdapter; private List<Estrela> estrelas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); EstrelaRepositorio estrelaRepositorio = new EstrelaRepositorio(this); estrelas = estrelaRepositorio.getStars(); estrelaAdapter = new EstrelaAdapter(estrelas, this); recyclerView.setAdapter(estrelaAdapter); } @Override public void onItemClick(Estrela estrela) { // Ao clicar em um item da lista, abrir a DetalheActivity Intent intent = new Intent(MainActivity.this, DetalheActivity.class); intent.putExtra("estrela_nome", estrela.getNome()); intent.putExtra("estrela_descricao", estrela.getDescricao()); startActivity(intent); } }
-
Estrela.java
public class Estrela { private String nome; private String descricao; public Estrela(String nome, String descricao) { this.nome = nome; this.descricao = descricao; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } @Override public String toString() { return "Estrela{" + "nome='" + nome + '\'' + '}'; } }
-
EstrelaRepositorio.java
import android.content.Context; import android.content.res.Resources; import java.util.ArrayList; import java.util.List; public class EstrelaRepositorio { private Context context; public EstrelaRepositorio(Context context) { this.context = context; } public List<Estrela> getStars() { List<Estrela> estrelas = new ArrayList<>(); Resources res = context.getResources(); estrelas.add(new Estrela(res.getString(R.string.estrela_1_nome), res.getString(R.string.estrela_1_descricao))); estrelas.add(new Estrela(res.getString(R.string.estrela_2_nome), res.getString(R.string.estrela_2_descricao))); estrelas.add(new Estrela(res.getString(R.string.estrela_3_nome), res.getString(R.string.estrela_3_descricao))); return estrelas; } }
-
EstrelaAdapter.java
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class EstrelaAdapter extends RecyclerView.Adapter<EstrelaAdapter.StarViewHolder> { private List<Estrela> estrelas; private OnItemClickListener listener; public interface OnItemClickListener { void onItemClick(Estrela estrela); } public EstrelaAdapter(List<Estrela> estrelas, OnItemClickListener listener) { this.estrelas = estrelas; this.listener = listener; } @Override public StarViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); return new StarViewHolder(view); } @Override public void onBindViewHolder(StarViewHolder holder, int position) { Estrela estrela = estrelas.get(position); holder.textView.setText(estrela.getNome()); } @Override public int getItemCount() { return estrelas.size(); } class StarViewHolder extends RecyclerView.ViewHolder { TextView textView; public StarViewHolder(View itemView) { super(itemView); textView = itemView.findViewById(android.R.id.text1); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(estrelas.get(getAdapterPosition())); } }); } } }
-
activity_detalhe.xml
<?xml version="1.0" encoding="utf-8"?> <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"/>
-
DetalheActivity.java
import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class DetalheActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalhe); String estrelaNome = getIntent().getStringExtra("estrela_nome"); String estrelaDescricao = getIntent().getStringExtra("estrela_descricao"); EstrelaFragment fragmento = EstrelaFragment.newInstance(estrelaNome, estrelaDescricao); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, fragmento) .commit(); } }
-
fragment_estrela.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:padding="16dp"> <TextView android:id="@+id/textviewNomeEstrela" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.AppCompat.Medium" android:textStyle="bold" /> <TextView android:id="@+id/textViewDescricao" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.AppCompat.Medium" android:layout_marginTop="8dp"/> </LinearLayout>
-
EstrelaFragment.java
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class EstrelaFragment extends Fragment { private static final String ARG_NOME = "nome"; private static final String ARG_DESCRICAO = "descricao"; private String estrelaNome; private String estrelaDescricao; public static EstrelaFragment newInstance(String nome, String descricao) { EstrelaFragment fragment = new EstrelaFragment(); Bundle args = new Bundle(); args.putString(ARG_NOME, nome); args.putString(ARG_DESCRICAO, descricao); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { estrelaNome = getArguments().getString(ARG_NOME); estrelaDescricao = getArguments().getString(ARG_DESCRICAO); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_estrela, container, false); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TextView textViewNome = view.findViewById(R.id.textviewNomeEstrela); TextView textViewDescricao = view.findViewById(R.id.textViewDescricao); textViewNome.setText(estrelaNome); textViewDescricao.setText(estrelaDescricao); } }