组件间通信

组件间通信

  1. EventBus实现通信

    在Activity注册EventBus,在Activity写入消息订阅接收消息,在fragment发送消息。

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String message) {
        mViewPager.setCurrentItem(0);
        mTab.setCurrentTab(0);
    }

在fragment发送消息

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EventBus.getDefault().post("000000");

        }
    });
  1. 接口回调

在fragment定义接口,并为接口赋值,Interface = (getActivity())interface.
在Activity实现接口即可。

ISubmit iSubmit;//定义接口对象

    public interface ISubmit {
            void refresh();
        }

interfaceBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            iSubmit = (ISubmit) getActivity();
            iSubmit.refresh();
        }
    }); 

在Activity实现接口即可

public class MainActivity extends BaseActivity implements MessageFragment.ISubmit {

          @Override
          public void refresh() {
        Toast.makeText(getApplicationContext(), "刷新了", Toast.LENGTH_LONG).show();

        }

    }
  1. Handler消息

在Activity创建handler对象,创建获取handler对象方法,在fragment中将getActivity()强转成当前Activity,再获取Handler对象,发送消息。

public Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 100:
                Toast.makeText(getApplicationContext(), "刷新了handler", Toast.LENGTH_LONG).show();
                mViewPager.setCurrentItem(0);
                mTab.setCurrentTab(0);
                break;
        }
    }
};


public Handler getHandler(){
    return handler;
}

在fragment中

 handler = ((MainActivity) mActivity).getHandler();

 handlerBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Message message = new Message();
            message.what = 100;
            handler.sendMessage(message);
        }
    });

你可能感兴趣的:(组件间通信)