Truyền dữ liệu giữa 2 fragment trong android

5/5 - (6 votes)

Ngữ cảnh

Ngữ cảnh là có 1 Activity chứa 2 fragment, 1 cái bên trên và 1 cái bên dưới, cả 2 fragment được tạo ra trong xml (không phải bằng java code). Fragment 1 chứa 1 cái input và 1 cái nút, người dùng sẽ nhập vào input và khi click nút thì sẽ setText cho TextView ở Fragment 2.

Tư tưởng

Để truyền dữ liệu giữa 2 fragment ta cần làm như sau: Fragment 1 truyền cho Activity, sau đó Activity truyền cho Fragment 2

Tại sao phải làm thế? Vì tính chất của activity và fragment. Không phải fragment 2 kia lúc nào cũng tồn tại trong host activity vì vậy ta phải chắc chắn fragment 2 tồn tại thì mới truyền.

Cách làm

Tạo 1 Interface sau đó bắt Activity chính lắng nghe sự kiện từ Interface đó, sau đó ở Fragment thứ nhất gọi hàm trong Interface và truyền dữ liệu cho hàm bên Activity, từ Activity tạo đối tượng Fragment 2 và gọi hàm trong Fragment setText cho nó,

Chi tiết Code

Tạo Interface CommunicationInterface.java

public interface CommunicationInterface {
    void onClickTopFragment(String str);
}

Tạo Activity CommunicationActivity.java

public class CommunicationActivity extends AppCompatActivity implements CommunicationInterface{

    SubBottom subBottomFrag;

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

    @Override
    public void onClickTopFragment(String str) {
        SubBottom fragBot = (SubBottom) getSupportFragmentManager().findFragmentById(R.id.fragment2);
          if (fragBot != null || fragBot.isInLayout()) { // kiểm tra Fragment cần truyền data đến có thực sự tồn tại và đang hiện.
            fragBot.updateFragmetn(str);
            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Khong tim thay, hoac fragment khong hien", Toast.LENGTH_SHORT).show();
        }
    }

}

Implement cái interface mà đã nói bên trên sau đó override hàm onClickTopFragment bắt buộc. Ở đây tạo luôn một đối tượng Fragment muốn gửi dữ lệu đến.

Tạo Fragment 1 SubTop.java

public class SubTop extends Fragment {
    Button btnClick;
    CommunicationInterface listener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CommunicationInterface) {
            listener = (CommunicationInterface) context;
        } else {
            throw new RuntimeException(context.toString() + "Can phai implement");
        }
    }
    public SubTop() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.top, container, false);
        btnClick = (Button) view.findViewById(R.id.button);
        final EditText edtText = (EditText) view.findViewById(R.id.editText);
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClickTopFragment(edtText.getText().toString());
            }
        });
        return view;
    }
}

Override hàm onAttach để kiểm tra xem cái Activity hện tại đã implement cái interface kia hay chưa.

Cùng với đó xử lí nút khi click và gọi hàm onClickTopFragment cho Activity nghe thấy.

Tao Fragment 2 SubBottom.java

import android.os.Bundle;
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;

import com.dttsolv.fragmentdemo.R;

public class SubBottom extends Fragment {

    TextView txtView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bottom, container, false);
        txtView = (TextView) view.findViewById(R.id.textView123);
        return view;
    }

    public void updateFragment(String str) {
        txtView.setText(str);
    }
}

Bên Fragment chỉ việc setText thôi.

Tham khảo thêm trên Stackoverflow tại link này

Ngoài ra:

Có thể truyền dữ liệu giữa 2 fragment bằng cách khác như dùng eventBus tham khảo thêm ở:

https://dotrinh.com/cach-dung-eventbus-de-truyen-du-lieu-trong-android/

https://saiandroidmotion.wordpress.com/2015/04/05/vi-du-truyen-du-lieu-giua-hai-fragment-bang-eventbus/

Các bài viết không xem thì tiếc:

2 Comments

Thảo luận

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Xem thêm
Để hiển thị chuẩn theo các size màn hình thì…
 
 
 
 
Facetime iPhone

Main Menu