การส่งข้อมูลระหว่าง Fragment โดยใช้ Interface และ ViewPager
ตัวอย่างนี้สาธิตวิธีส่งข้อความจาก FragmentOne ไปยัง FragmentTwo ผ่าน Interface ที่ MainActivity ทำหน้าที่เป็นกลาง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
ไปที่ File → New Project ใน Android Studio
ขั้นตอนที่ 2: Layout หลัก (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
ขั้นตอนที่ 3: สร้าง Fragment ทั้งสอง
FragmentOne.java - มีช่องกรอกข้อความและปุ่มส่ง
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
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 FragmentOne extends Fragment {
private SendMessage sendMessage;
public FragmentOne() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_fragment_one, container, false);
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = view.findViewById(R.id.btnPassData);
final EditText inData = view.findViewById(R.id.passMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
try {
sendMessage = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
fragment_fragment_one.xml
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:fillViewport="true">
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="@+id/passMessage" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_above="@+id/btnPassData"
android:layout_margin="16dp" android:hint="Enter here" />
<Button android:id="@+id/btnPassData" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true"
android:text="PASS DATA TO FRAGMENT TWO" />
</RelativeLayout>
</ScrollView>
FragmentTwo.java - รับและแสดงข้อมูล
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.TextView;
public class FragmentTwo extends Fragment {
private TextView textView;
public FragmentTwo() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_fragment_two, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = view.findViewById(R.id.txtData);
}
void displayReceivedData(String message) {
textView.setText("Data received: " + message);
}
}
fragment_fragment_two.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".FragmentTwo">
<TextView android:id="@+id/txtData" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="20sp"
android:textStyle="bold" android:layout_centerInParent="true"
android:text="No data received" />
</RelativeLayout>
ขั้นตอนที่ 4: MainActivity.java (ทำหน้าที่กลาง)
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.viewPager + ":" + 1;
FragmentTwo f = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
ขั้นตอนที่ 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>
การทดสอบ
รันแอป กรอกข้อความใน FragmentOne แล้วกดปุ่ม จะส่งข้อมูลไปแสดงใน FragmentTwo ทันที