I have default Master-Detail flow, which was created automatically when creating new project. My question is. When I add a button to detail side. Is there a way to update my list side by pressing that button ? In other words, can ItemDetailFragment and ItemListFragment communicate ?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes just communicate through the activity with a listener.
Your activity:
public class MyActivity extends FragmentActivity implements OnFragmentClickListener {
@Override
public void OnFragmentClick(int action, Object object) {
switch(action) {
}
}
}
The listener class:
public interface OnFragmentClickListener {
public void OnFragmentClick(int action, Object object);
}
Your fragments will then have following somewhere in code in order to implement the interface:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement listeners!");
}
}
Then your fragments communicate with each other like this: fragmentA -> activity -> fragmentB. Your activity can call methodes directly on the fragments without worrying about synchronization problems.
Example of a call from fragment a:
mListener.OnFragmentClick(GLOBAL_ACTION_KEY someObject);
Activity then handle:
public class MyActivity extends FragmentActivity implements OnFragmentClickListener {
@Override
public void OnFragmentClick(int action, Object object) {
switch(action) {
case GLOBAL_ACTION_KEY:
// you call fragmentB.someMethod();
break;
}
}
}