'Why I can't send data from child fragment to parent fragment?
I have a parent fragment with 2 children fragments (home, detail).
Inside the parent fragment, there are 2 button to change both children fragment: btn_home
and btn_detail
.
When I click the button in the Home fragment, btn_home_button
, the fragment will change to Detail fragment, and when clicking on btn_detail
it will change color.
When I click btn_home
to return Home fragment, it works. When try on click in Home fragment, btn_home_button
, to change the fragment it works work too. However, the btn_detail
button doesn't change the color.
// this is home fragment, there is button to click
//change fragment
//send data to parent fragment to it know and change button color in parent fragment
private void clickButton(Button btn, int distinguish) {
Bundle bundle = new Bundle();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bundle.putInt("key", distinguish);
getParentFragmentManager().setFragmentResult("requestKeyFromButton", bundle);
changeFragment(DetailFragment.class);
}
});
}
//this is parent fragment
// it receive data form Home fragment
// change button color
private void receiptDataFromMainHome() {
Log.d("current", "loaded again");
getParentFragmentManager().setFragmentResultListener(
"requestKeyFromButton",
this,
new FragmentResultListener() {
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
Log.d("current", "receive data");
if (result != null) {
int distinguish = result.getInt("key");
if (distinguish > 0) {
Log.d("adad", "1: " + distinguish);
choseButtonChange(btnPlaylist, distinguish);
}
}
}
}
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|