android的Fragment和Activity发送广播通信
2019-02-17 本文已影响0人
心中有梦丶身边有你
遇到一个需求是要求点击Fragment中的某个按钮,跳转到另一个Fragment
一般的Fragment之间的跳转是这样的:
getFragmentManager()
.beginTransaction()
.addToBackStack(null) //将当前fragment加入到返回栈中
.replace(R.id.xx, new FragmentTwo())
//第一个是在你activity中的framlayout的id,第二个是你要跳转的Fragment
.commit();
但是有些时候他会跳转页面,可是下面的底部导航栏没有反应, 我就写了个广播,点击按钮的时候,告诉Activity,需要切换Fragment显示,代码如下:
Fragment
private SendBtnListener mSendBtnListener;
public FragmentTwo() {
}
public interface SendBtnListener{
public void sendBtnClick();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof SendBtnListener){
mSendBtnListener = (SendBtnListener)context;
}
else {
throw new ClassCastException(context.toString()+"must implement SendBtnListener!");
}
}
点击的时候,加入下面这一句:
mSendBtnListener.sendBtnClick();
MaiActivity中接收广播做出反应
@Override
public void sendBtnClick() {
//这里写你接收到广播之后需要做的操作
}