Activity调用 Fragment
- 1 直接调用
//findFragmentById 或者 findFragmentByTag
if (getSupportFragmentManager().findFragmentById(R.id.a_fragment) instanceof AFragment ){
AFragment aFragment = (AFragment ) getSupportFragmentManager().findFragmentById(R.id.a_fragment);
aFragment.doSomeThing();
}
- 2 广播发送监听
- 3 EventBus消息总线发送监听
- 4 单例模式处理
Fragment 调用 Activity
- 1 直接调用
if (getActivity() instanceof MainActivity){
MainActivity mainActivity=(MainActivity) getActivity();
mainActivity.doSomeThing();
}
- 2 接口调用
Fragment 中定义一个接口
private OnFragmentInteractionListener mListener;
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
//某操作 执行这个方法
public void doSomeThing{
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
Activity 实现这个接口
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onFragmentInteraction(Uri uri) {
//todo
}
}
- 3 广播发送监听
- 4 EventBus消息总线发送监听
- 5 单例模式处理