Câu hỏi phỏng vấn Android
Câu hỏi

How would you communicate between two Fragments?

Câu trả lời

Here are a few ways to communicate between two Fragments in Android:

Using an Interface Callback

  1. Define an interface in the parent Activity that will hold references to both Fragments.
  2. Have each Fragment implement this interface and pass a reference to itself to the Activity when created.
  3. The Activity can then call methods on the interface to pass data between the Fragments.
java Copy
public class ParentActivity extends AppCompatActivity implements FragmentCallback {
    
    @Override
    public void onDataPassed(String data) {
        // Call this method to pass data to Fragment2
        fragment2.updateData(data);
    }
}

public class Fragment1 extends Fragment {
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ((ParentActivity) context).setFragment1(this);
    }
    
    // Call this method to pass data to Fragment2
    public void passDataToFragment2(String data) {
        ((ParentActivity) getActivity()).onDataPassed(data);
    }
}

Using a ViewModel

  1. Create a ViewModel class that will hold the shared data.
  2. Have both Fragments observe the ViewModel's LiveData.
  3. Update the ViewModel's data from either Fragment to trigger updates in the other.
java Copy
public class SharedViewModel extends ViewModel {
    private final MutableLiveData<String> selectedItem = new MutableLiveData<String>();

    public void select(String item) {
        selectedItem.setValue(item);
    }

    public LiveData<String> getSelectedItem() {
        return selectedItem;
    }
}

public class Fragment1 extends F...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is the most appropriate way to store user settings in Android application?

middle

What is the difference between Service & Intent Service ?

middle

What is the difference between compileSdkVersion and targetSdkVersion ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào