Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

บทเรียน Fragment พร้อมตัวอย่างใน Android Studio

ตัวอย่างนี้สาธิต Fragment Tutorial พร้อมตัวอย่างใน Android Studio

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio

ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นทั้งหมด

ขั้นตอนที่ 2: เพิ่มโค้ดใน 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"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <Button
        android:id="@+id/fragment1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="27dp"
        android:text="fragment1"/>
    <Button
        android:id="@+id/fragment2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="27dp"
        android:text="fragment2"/>
    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    </LinearLayout>
</LinearLayout>

ใช้ปุ่ม (Button) และ LinearLayout เพื่อแสดง Fragment ต่างๆ

ขั้นตอนที่ 3: เพิ่มโค้ดใน src/MainActivity.java

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) {
                android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
                android.support.v4.app.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();
            }
        });
    }
}

ขั้นตอนที่ 4: เพิ่มโค้ดใน src/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");
        return view;
    }
}

ขั้นตอนที่ 5: เพิ่มโค้ดใน src/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");
        return view;
    }
}

ขั้นตอนที่ 6: เพิ่มโค้ดใน 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:gravity="center"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

การทดสอบแอปพลิเคชัน

รันแอปพลิเคชันบนอุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอเริ่มต้น

บทเรียน Fragment พร้อมตัวอย่างใน Android Studio

คลิกที่ปุ่ม จะแสดง Fragment ต่างๆ ตามภาพ

บทเรียน Fragment พร้อมตัวอย่างใน Android Studio

บทเรียน Fragment พร้อมตัวอย่างใน Android Studio

แนวทางปฏิบัติที่ดี (Best Practices) สำหรับ Fragment

  • ใช้ FragmentContainerView แทน FrameLayout/LinearLayout ใน API ใหม่ๆ
  • หลีกเลี่ยงการใช้ @SuppressLint("ValidFragment") - ควรสร้าง Constructor ไม่มีพารามิเตอร์
  • ใช้ ViewBinding หรือ DataBinding แทน findViewById
  • จัดการ Lifecycle อย่างถูกต้องด้วย onStart, onResume, onPause, onStop
  • สำหรับโปรเจกต์ใหม่ ควรใช้ AndroidX (androidx.fragment.app.Fragment) แทน Support Library