Quá trình giao tiếp sẽ diễn ra như sau:chúng ta sẽ nhập thông tin vào EditText và nhấn chuột trái vào Button trong fragment thứ nhất. Nội dung trong EditText sẽ hiển thị trong TextView của fragment thứ hai. Fragment thứ nhất (First Fragment) không thể giao tiếp trực tiếp với fragment thứ hai (Second Fragment) mà phải thông qua Activity. Quá trình giao tiếp có thể trực quan như sau:

Chúng ta sẽ đề cập giai đoạn thứ nhất.

Giai đoạn 1: Fragment thứ nhất giao tiếp với Activity

Khi người dùng nhấp chuột vào Button trên fragment thứ nhất, lớp fragment thứ nhất cần lấy giá trị từ EditText và chuyển giá trị này đến fragment thứ hai. Quá trình này diễn ra thông qua Activity gồm các bước sau:

Bước 1: đảm bảo fragment thứ nhất đưa ra phản ứng (hay xử lý sự kiện) khi người dùng nhấp chuột vào Button. Để thực hiện điều này chúng ta cần tham chiếu đến các đối tượng (Button và EditText) trên layout của fragment thứ nhất và thiết lập trình lắng nghe sự kiện Click cho Button. Mở tập tin FirstFragment.java và thêm các lệnh sau:


package com.ngocminhtran.fragmentexample;

import android.content.Context;
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.Button;
import android.widget.EditText;

public class FirstFragment  extends Fragment  {

private static EditText edittext;


@Override
public View onCreateView(LayoutInflater inflater,
     ViewGroup container, Bundle savedInstanceState) {

      // Inflate the layout for this fragment
      View view = inflater.inflate(R.layout.layout_first_fragment, 
             container, false);

      edittext = (EditText) view.findViewById(R.id.editText1);

      final Button button = (Button) view.findViewById(R.id.button1);

      button.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
                buttonClicked(v);
          }
      });

     return view;
}

public void buttonClicked (View view) {
}
}

Khi người dùng nhấn chuột vào Button lớp FirstFragment sẽ thực hiện phương thức buttonClicked.

Bước 2: cài đặt một giao diện lắng nghe cho phép fragment thứ nhất gọi Activity khi người dùng nhấn vào Button. Để thực hiện điều này chúng ta sẽ bổ sung đoạn mã sau vào đẩu lớp FirstFragment:


public class FirstFragment  extends Fragment  {

    private static EditText edittext;

    FirstFragmentListener activityCallback;
    public interface FirstFragmentListener {
        public void onButtonClick(int fontsize, String text);
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
              activityCallback = (FirstFragmentListener) context;
            } catch (ClassCastException e) {
                 throw new ClassCastException(context.toString()
                     + " You must implement FirstFragmentListener");
            }
       }

...}

Chúng ta cài đặt giao diện FirstFragmentListener và sử dụng phương thức onAttach() của lớp Fragment để kết nối đến Activity. Khi Button được nhấn, Activity sẽ được gọi bằng cách bổ sung đoạn mã sau vào phương thức buttonClicked:


public void buttonClicked (View view) {
    activityCallback.onButtonClick(20,edittext.getText().toString());
}

Bước 3: Vì Activity sẽ giao tiếp với các fragments nên lớp Activity, thay vì kế thừa lớp AppCompatActivity, sẽ kế thừa lớp FragmentActivity. Mở tập tin FragmentExampleActivity.java và thay đổi như sau:


package com.ngocminhtran.fragmentexample;


import android.support.v4.app.FragmentActivity;
import android.os.Bundle;


public class FragmentExampleActivity extends FragmentActivity  {

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

   }

}

Vì chúng ta muốn Activity lắng nghe sự kiện từ fragment thứ nhất nên lớp FragmentExampleActivity phải thực thi giao diện FirstFragmentListener:


public class FragmentExampleActivity extends FragmentActivity
implements FirstFragment.FirstFragmentListener {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fragment_example);
     }
     public void onButtonClick(int fontsize, String text) {

     }
}

Lúc này Activity đã tiếp nhận sự kiện từ fragment và chuẩn bị cho việc giao tiếp với fragment thứ hai.

Giai đoạn 2: Activity giao tiếp với Fragment thứ hai

Giá trị nhận được từ EditText của fragment thứ nhất sẽ được Activity chuyển đến TextView trong fragment thứ hai. Lớp Activity xác định fragment thứ hai thông qua ID của fragment này (second_fragment). Trước khi thực hiện một số thay đổi trong lớp Activity chúng ta cần tham chiếu đến đối tượng TextView trong layout của fragment thứ hai và thực hiện phương thức changeTextProperties() để thay đổi kích cỡ chữ và nội dung từ EditText(trong fragment thứ nhất). Mở tập tin SecondFragment.java và thực hiện các thay đổi sau:


package com.ngocminhtran.fragmentexample;
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 SecondFragment extends Fragment  {

    private static TextView textview;
    @Override
    public View onCreateView(LayoutInflater inflater,
           ViewGroup container, Bundle savedInstanceState) {
         View view = inflater.inflate(R.layout.layout_second_fragment, 
             container, false);

         textview = (TextView) view.findViewById(R.id.textView1);

         return view;
    }
    public void changeTextProperties(int fontsize, String text)
    {
       textview.setTextSize(fontsize);
       textview.setText(text);
    }
}

Bây giờ chúng ta sẽ thực hiện một số bổ sung trong lớp Activity bằng cách mở tập tin FragmentExampleActivity.java và thêm các đoạn mã sau vào phương thức onButtonClick:


public void onButtonClick(int fontsize, String text) {
   SecondFragment textFragment =          
        SecondFragment)getSupportFragmentManager().findFragmentById
                 (R.id.second_fragment);
   textFragment.changeTextProperties(fontsize, text);
}

Đến thời điểm này chúng ta đã hoàn tất ứng dụng.

Fragments trong Android >