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

四大组件之间传递数据可以用广播,但是有次面试官说太重了,用eventbus代替。下面的广播传递数据方法仅当学习参考。

1.管理类

 

/**
 * 广播管理类:注册广播、注销广播、发送广播
 * @author weizh_000
 * @date 2016-8-29
 */
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);
    }
    
}

 

2.发送广播

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之间也可以这样传数据。

 

posted @ 2016-08-29 23:02  达哥的博客  阅读(5357)  评论(0编辑  收藏  举报