Home >Java >javaTutorial >Mastering Fragments in Java for Android Development
Fragments are a crucial component in Android development, providing a modular and reusable architecture for creating dynamic user interfaces. A fragment represents a portion of a user interface within an activity, allowing for more flexible and manageable UI designs, especially on larger screens. This article will guide you through the fundamentals of fragments in Java, their lifecycle, and how to implement them in your Android projects.
A fragment's lifecycle is closely tied to the lifecycle of its host activity but with additional states. Here are the key stages:
Step 1: Create a Fragment Class
To create a fragment, extend the Fragment class and override necessary lifecycle methods.
public class MyFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_my, container, false); } }
Step 2: Define the Fragment Layout
Create an XML layout file for the fragment (e.g., fragment_my.xml) in the res/layout directory.
<?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/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, Fragment!" android:textSize="18sp"/> </LinearLayout>
Step 3: Add the Fragment to an Activity
In your activity's layout XML file, use a FragmentContainerView to define where the fragment will be placed.
<androidx.fragment.app.FragmentContainerView android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"/>
Step 4: Display the Fragment in the Activity
In your activity, use FragmentManager to add or replace the fragment within the FragmentContainerView.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new MyFragment()) .commit(); } } }
The above is the detailed content of Mastering Fragments in Java for Android Development. For more information, please follow other related articles on the PHP Chinese website!