欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Fragment和Activity之间通过广播的方式传递数据

程序员文章站 2024-03-15 15:12:09
...

1.管理类

/**
 * 广播管理类:注册广播、注销广播、发送广播
 * @author Monster_y
 * @date 2019-7-30
 */
public class BroadCastManager {

    private static BroadCastManager broadCastManager = new BroadCastManager();

    public static BroadCastManager getInstance() {
        return broadCastManager;
    }

    //注册广播接收者
    public void registerReceiver(Activity activity,
            BroadcastReceiver receiver, IntentFilter filter) {
        activity.registerReceiver(receiver, filter);
    }
    
    //注销广播接收者
    public void unregisterReceiver(Activity activity,
            BroadcastReceiver receiver) {
        activity.unregisterReceiver(receiver);
    }

    //发送广播
    public void sendBroadCast(Activity activity, Intent intent) {
        activity.sendBroadcast(intent);
    }
    
}

发送广播

public class MyFragment extends Fragment {

    private String orderid = "85465465";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        
        //发送广播
        Intent intent = new Intent();
        intent.putExtra("order", orderid);
        intent.setAction("fragment_home_left");
        BroadCastManager.getInstance().sendBroadCast(getActivity(), intent);
        
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
}

3.接受广播

public class MainActivity extends ActionBarActivity {

    private LocalReceiver mReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //接收广播
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("fragment_home_left");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(this,
                    mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    class LocalReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            String orderid = intent.getStringExtra("order");
            loadData(orderid);            
        }
        
    }
    
    
    private void loadData(String orderid){
        
    }
    
    @Override
    protected void onDestroy() {
        BroadCastManager.getInstance().unregisterReceiver(this,mReceiver);//注销广播接收者
        super.onDestroy();
    }
    
}

上面的例子是fragment传递数据给Activity,其实Activity也可以通过广播的方式传递数据给fragment,还有fragment与fragment之间也可以这样传数据。