Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Hướng dẫn Fragment cơ bản với ví dụ trên Android Studio

Fragment Tutorial - Cơ bản về Fragment trong Android

Fragment đại diện cho một phần giao diện người dùng hoặc hành vi trong một Activity. Có thể kết hợp nhiều fragment trong một activity để xây dựng giao diện đa pane, và fragment có thể được tái sử dụng trong nhiều activity.

Bước 1: Tạo dự án mới

Tạo project Android Studio mới.

Bước 2: Layout chính (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/fragment1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="27dp"
        android:layout_gravity="center_horizontal"
        android:text="Fragment 1" />

    <Button
        android:id="@+id/fragment2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="27dp"
        android:layout_gravity="center_horizontal"
        android:text="Fragment 2" />

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>

</LinearLayout>

Hai nút bấm để chuyển đổi giữa 2 fragment, và một container (LinearLayout) để chứa fragment.

Bước 3: MainActivity.java - Quản lý Fragment

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final android.support.v4.app.Fragment first = new FirstFragment();
        final android.support.v4.app.Fragment second = new SecondFragment();
        
        findViewById(R.id.fragment1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                fragmentTransaction.replace(R.id.layout, first);
                fragmentTransaction.commit();
            }
        });
        
        findViewById(R.id.fragment2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                fragmentTransaction.replace(R.id.layout, second);
                fragmentTransaction.commit();
            }
        });
    }
}

Bước 4: FirstFragment.java

package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class FirstFragment extends Fragment {
    TextView textView;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        textView = view.findViewById(R.id.text);
        textView.setText("First Fragment");
        return view;
    }
}

Bước 5: SecondFragment.java

package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SecondFragment extends Fragment {
    TextView textView;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        textView = view.findViewById(R.id.text);
        textView.setText("Second Fragment");
        return view;
    }
}

Bước 6: Layout fragment chung (res/layout/fragment.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp" />

</LinearLayout>

Chạy ứng dụng

Màn hình chính có 2 nút "Fragment 1" và "Fragment 2". Click vào từng nút sẽ thay thế container bằng fragment tương ứng, hiển thị text "First Fragment" hoặc "Second Fragment".

Lưu ý quan trọng

  • Sử dụng getSupportFragmentManager() để tương thích ngược
  • FragmentTransaction.replace() thay thế fragment hiện tại trong container
  • Luôn gọi commit() để áp dụng thay đổi
  • Fragment layout được inflate trong onCreateView()