How would you communicate between two Fragments?
How would you communicate between two Fragments?
Here are a few ways to communicate between two Fragments in Android:
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);
}
}
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào