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

วิธีส่งข้อมูลจาก Activity ไป Fragment ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการส่งข้อมูล (Variable) จาก Activity ไปยัง Fragment โดยใช้ Bundle และ setArguments()

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

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดทำ Layout หลัก (res/layout/activity_main.xml)

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

    <EditText
        android:id="@+id/editText"
        android:layout_marginTop="20sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ป้อนข้อความของคุณ" />

    <Button
        android:id="@+id/btnSendData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ส่งข้อมูล" />

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        final MyFragment myFragment = new MyFragment();

        button = findViewById(R.id.btnSendData);
        editText = findViewById(R.id.editText);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle b = new Bundle();
                b.putString("message", editText.getText().toString());
                myFragment.setArguments(b);

                // เพิ่ม Fragment ลงใน Container
                fragmentTransaction.add(R.id.frameLayout, myFragment).commit();
            }
        });
    }
}

ขั้นตอนที่ 4: สร้าง Fragment (MyFragment.java และ fragment_my.xml)

MyFragment.java

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

public class MyFragment extends Fragment {
    TextView textView;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        textView = view.findViewById(R.id.textView);

        Bundle bundle = getArguments();
        if (bundle != null) {
            String message = bundle.getString("message");
            textView.setText(message);
        }
        return view;
    }
}

res/layout/fragment_my.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/textView"
        android:textSize="30dp"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ขั้นตอนที่ 5: กำหนดค่า AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

วิธีส่งข้อมูลไป Fragment อื่นๆ

วิธี คำอธิบาย
Bundle + setArguments() มาตรฐาน ส่งข้อมูลตอนสร้าง Fragment (แนะนำ)
Interface/Callback Fragment เรียก Interface ของ Activity เพื่อขอข้อมูล
ViewModel (Shared) ใช้ ViewModel ร่วมกัน (Architecture Components) - แนะนำสำหรับแอปใหม่
Static method newInstance() Pattern แบบ Factory Method สร้าง Fragment พร้อม Argument

Pattern newInstance() (แนะนำ)

public static MyFragment newInstance(String message) {
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    args.putString("message", message);
    fragment.setArguments(args);
    return fragment;
}

// การใช้งาน:
MyFragment fragment = MyFragment.newInstance("Hello Fragment");

การทดสอบ

รันแอป พิมพ์ข้อความ กด "ส่งข้อมูล\" จะแสดง Fragment พร้อมข้อความที่ส่งมา

วิธีส่งข้อมูลจาก Activity ไป Fragment ใน Android